【问题标题】:Creating a function to edit a list with a variable number and given string创建一个函数来编辑具有变量编号和给定字符串的列表
【发布时间】:2014-01-06 01:39:15
【问题描述】:

我正在尝试创建一个带有两个参数的函数,一个数字和一个字符串。我需要能够用一个数字 n 调用它,以便将 theList 的第 n 个元素修改为从函数中读取为字符串。
我是一个初学者,所以我为此苦苦挣扎——我知道我目前在函数中拥有的不是我所需要的,但我希望将它作为我可以适应的起点。我在想我可能需要使用循环来做到这一点......除此之外,我没有很多想法。有什么指导吗?

<html>

<script>

function doit() {
document.getElementById('element1').innerHTML='Element one';
document.getElementById('element2').innerHTML='Element two';
document.getElementById('element3').innerHTML='Element three';
}
</script>
<body>
<p>Value: <input type="text" id="theInput" value="" size=10>
<input type="button" id="theButton" value="click me!" onclick="doit()"></p>
<ul id="theList">
<li id="element1">Element 1
<li id="element2">Element 2
<li id="element3">Element 3
</ul>
<div id="theDiv"></div>
</body>
</html>

【问题讨论】:

  • 你的 li 元素没有结束标签。

标签: javascript list function loops


【解决方案1】:

您可以使用 jQuery 来获取 ul 标记的子 (li) 元素。它将返回一个包含所有孩子的数组。请注意,数组是零索引的。传入索引时需要牢记这一点,或者将代码从索引更新为 -1。

function updateListItem(index, text) {
    var myListItem = $("#theList").children()[index]; // DOM reference to the list item

    $(myListItem).text(text); // update the text
}

没有 jQuery,你可以这样做:

function updateListItem(index, text) {
    var myListItem = document.getElementById("theList").children[index] // An array of the list items
    myListItem.innerHTML = text; // update the text
}

【讨论】:

    【解决方案2】:

    这里有一些关于你应该做什么的想法:

    1. 对于函数doit,需要添加两个参数,分别代表字符串和数字。
    2. 接下来,创建一个变量,它是“元素”和您的数字参数的串联(字符串添加)
    3. 最后,使用上述方法将document.getElementById(&lt;your string here&gt;) 设置为您的字符串。

    这是一个快速实现的示例:

    function doit(str, num){
      var elementID = "element" + num;
      document.getElementById(elementID).innerHTML = str;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-20
      • 2021-12-10
      • 1970-01-01
      • 2020-08-11
      • 1970-01-01
      • 1970-01-01
      • 2021-08-14
      • 2022-09-30
      相关资源
      最近更新 更多