gpt4 book ai didi

javascript - 函数带有标签和值的东西需要两个字符串

转载 作者:行者123 更新时间:2023-11-28 06:40:41 24 4
gpt4 key购买 nike

我有一个问题,我花了几个小时试图弄清楚,但问题是,我不知道我被要求做什么,所以我什至不知道从哪里开始回答这个问题。我在编码方面非常没有受过教育,完全不知道我的第一步是什么以及我将如何解决这个问题。该问题提供了 HTML 代码并询问我以下问题:

Write a function replace(tag, value) that takes two strings as argument. The first is a tag (e.g, "item" (without quotes) and the second is a replacement value (e.g., "flux capacitor" (without quotes). This function should replace the innerHTML of the element with the given tag with the specified value. If the tag does not exist your function should display an alert to indicate that the tag was not found. Test your code by defining the format() function which is tied to the Format button by replacing 'salutation' with 'Mr. Smith', 'invoice' with 123, 'item' with 'flux capacitor' and 'threaten' with 'Please do not make me angry.'

Write a function clearit() that removes all of the content from thepage contained within the tag with id='buttons'. Do not assume thatthe 'buttons' tag only contains two items.

html 代码如下:

<html>
<head>
<script src="q1.js" type="text/javascript"> </script>
</head>
<body>
Dear <span id="salutation">Name</span>;
<p>
It has come to our attention that your invoice <span id="invoice">ID</span>
has yet to be paid. It has now been <span id="time">some time</span> since
you received <span id="item">the material</span> from Evil Incorporated. Please
remit payment immediately. <span id="threaten"></span>
</p>
Yours sincerely,<br>
<br/>
<br/>
J. Smith, Accounting
<div id="buttons">
<center>
<button onclick="format()">Format</button>
<button onclick="clearit()">Clear</button>
</center>
</div>
</body>
</html>

最佳答案

为了帮助您入门,我使用您可以逐步填写的函数对规范进行了注释。请注意,我们不能使用 getElementsByTagName,因为 Replace 不接受参数来指定它应该使用可能的多个标签中的哪一个。因此,我假设规范在谈到标签时实际上是指 ID。

// `id` and `value` are Strings
function replace(id, value) {

// Get the element with id `id`
var elmt = /* (Task 1) Look into `document.getElementById` */

// If the element is not found, display an alert.
if (/* (Task 2) Check if `elmt` is falsy */) {

// (Task 3) Display the alert here.

// Otherwise, replace the contents.
} else {

// (Task 4) set `elmt`'s innerHTML to `value`.

}

}

这是测试助手。

function format() {
replace('salutation', 'Mr. Smith');
replace('invoice', '123');
replace('item', 'flux capacitor');
replace('threaten', 'Please do not make me angry.');
}

function clearit() {
replace('buttons', '');
}

关于javascript - 函数带有标签和值的东西需要两个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33853021/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com