jQuery document.getElementsByClassName().innerHTML 总是返回“未定义”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17896746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
document.getElementsByClassName().innerHTML always returns "undefined"
提问by Blaze Tama
I must have made a mistake somewhere so the document.getElementsByClassName().innerHTMLis always returning undefined.
我一定是在某个地方犯了一个错误,所以document.getElementsByClassName().innerHTML总是返回undefined。
First i generate the <li>via javascript :
首先,我<li>通过 javascript生成:
$('#list').append('<li class="box"><img class="picture" src="images/HotPromo/tagPhoto1.png"/><p class="name"><b>Name</b></p><p class="address">Address</p><p class="hidden"></p></li>');
Note that in the most right i have a <p>element with hiddenclass. I use this to get the idwhich i dont want to show to my users.
请注意,在最右边我有一个<p>带有hidden类的元素。我用它来获取我不想向我的用户显示的ID。
And this is the jQuery to generate the data on those <li>:
这是生成这些数据的 jQuery <li>:
$(".box").each(function () {
var name, address, picture, id = "";
if (i < result.length) {
name = result[i].name;
address = result[i].address;
picture = result[i].boxpicture;
id = result[i].mallid;
}
$(this).find(".name").html(name);
$(this).find(".address").html(address);
$(this).find(".picture").attr("src", picture);
$(this).find(".hidden").html(id);
i++;
});
I have tried to check the data, and its working fine.
我试图检查数据,它工作正常。
Now, lets say i want to alert the hidden id<p>when user clicks one of those <li class="box">that i generated above:
现在,假设我想在用户单击我在上面生成的ID 之一<p>时提醒隐藏的ID<li class="box">:
$(".box").click(function () {
alert(document.getElementsByClassName('hidden').innerHTML);
});
However this alert always returning "undifined".
但是,此警报始终返回“未定义”。
回答by adeneo
document.getElementsByClassName()returns a nodeList, not an element!
document.getElementsByClassName()返回一个 nodeList,而不是一个元素!
So it should be :
所以应该是:
document.getElementsByClassName('hidden')[0].innerHTML
and as you probably have more .hiddenelements, and only want the one inside the current .box(which would be thisin the event handler)
并且因为您可能有更多.hidden元素,并且只想要当前中的元素.box(将this在事件处理程序中)
this.getElementsByClassName('hidden')[0].innerHTML
but why not jQuery
但为什么不是 jQuery
$(".box").click(function(){
alert( $('.hidden', this).html() );
});

