Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/441.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Javascript中循环和设置第二个跨度的值?_Javascript_Jquery - Fatal编程技术网

如何在Javascript中循环和设置第二个跨度的值?

如何在Javascript中循环和设置第二个跨度的值?,javascript,jquery,Javascript,Jquery,我有一个查询,我想在其中设置div中第二个span的值 <div id="content"> <h1>Welcome</h1> <span>This is the first span</span> <span>This is the second span</span> <span>This is the 3rd span</span> </

我有一个查询,我想在其中设置div中第二个span的值

<div id="content">
    <h1>Welcome</h1>
    <span>This is the first span</span>
    <span>This is the second span</span>
    <span>This is the 3rd span</span>
    </div>

欢迎
这是第一个跨度
这是第二个跨度
这是第三跨
我正在使用以下javascript

function SetValue(myValue) {

            var mainDiv = document.getElementById("content");
            for(var i=0;i<mainDiv.childNodes.length;i++) {
               if(mainDiv.childNodes[i] == 2) {
                   mainDiv.childNodes[i].innerText = myValue;
               }


            }
        }
函数设置值(myValue){
var mainDiv=document.getElementById(“内容”);
对于(var i=0;i,只需使用.eq()函数

.eq函数从索引0开始


这是演示

内部
设置值
,使用这一行:

$(“#内容跨度:eq(1)”).html(myValue);

不需要循环或其他任何东西

文件


这项工作的复杂性:

这个纯JS实现怎么样,因为除了标记之外,没有任何迹象表明JQuery是一个选项,对于这样的东西完全不需要它:

function SetValue(myValue){
    document.getElementById("content").getElementsByTagName("span")[1].innerText = myValue;
}
这可能会有帮助:

$(function() {
  $('#content span:nth-child(2)').text('your text');
});​

if语句必须检查mainDiv.childNodes[i]。tagName==“span”
并增加一个计数器,在找到第二个后设置innerText。或者(我认为更好)已经发布了几个使用N个子css选择器的jQuery建议。

您发布的代码是否不起作用?您的问题是什么?@MoizKachwala:没有理由循环,对于大多数浏览器,您需要使用
。children
而不是
。childrenodes
,以及
而不是
。textContent
而不是
。innerText
var span=document.getElementById(“content”).children[2];span.textContent=span.innerText=myValue;
*一旦找到第二个,我就有一个查询,我想通过循环child中的元素来完成。@Gromer:小提琴显示它不起作用。你的目标范围不正确。这让它更清楚一点。
$(function() {
  $('#content span:nth-child(2)').text('your text');
});​