javascript 一起使用 getElementById 和 getElementsByTagName
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23645408/
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
Using getElementById and getElementsByTagName together
提问by L84
I have code that looks like so:
我有这样的代码:
<ul id="effects-list" class="effects-list">
<li data-creative="5">Creative</li>
</ul>
I am attempting to read the data attribute of that above HTML using the following code:
我正在尝试使用以下代码读取上述 HTML 的数据属性:
var effectData = document.getElementById("effects-list").getElementsByTagName("li");
var creative = effectData.getAttribute('data-creative');
alert(creative)
The above code doesn't work. It throws the following error:
上面的代码不起作用。它引发以下错误:
effectData.getAttribute is not a function
I am using jQuery on the page and originally tried this:
我在页面上使用 jQuery,最初尝试过这个:
var effectData = $('.effects-list li');
Again, same error.
再次,同样的错误。
What do I have wrong and how do I fix this?
我有什么问题,我该如何解决?
Here is a jsFiddleof the code.
这是代码的jsFiddle。
Note: There are more li
elements on the page and I am reading more data than just one li
element. I am trying to avoid having to ad a separate id to each li
element if I can help it.
注意:li
页面上有更多元素,我阅读的数据不仅仅是一个li
元素。li
如果可以的话,我试图避免为每个元素添加单独的 id 。
回答by Felix
getElementsByTagName()returns a list of elements with the given tag name, so you need to access the element inside this list using []
:
getElementsByTagName()返回具有给定标签名称的元素列表,因此您需要使用以下方法访问此列表中的元素[]
:
var effectData = document.getElementById("effects-list").getElementsByTagName("li")[0];
If you're looking for jQuery solution, you can use .data():
如果您正在寻找 jQuery 解决方案,您可以使用.data():
var creative = $('#effects-list').find('li').data('creative');
回答by Bhushan Kawadkar
Try below code
试试下面的代码
var dataCreative = $("#effects-list li").attr('data-creative');
alert(dataCreative);
This is working JSFiddle.
这是工作JSFiddle。
And if there are multiple li
inside ul
then you can use .each
, see below code
如果里面有多个li
,ul
那么你可以使用.each
,见下面的代码
$("#effects-list li").each(function(){
var dataCreative = $(this).attr('data-creative');
alert(dataCreative);
});