Selecting custom data attributes in JQuery

爷,独闯天下 提交于 2020-01-02 01:48:14

问题


I have a list here

<ul id="demo2" data-name="demo2">
    <li data-value="here">here</li>
    <li data-value="are">are</li>
    <li data-value="some...">some</li>
    <!-- notice that this tag is setting a different value :) -->
    <li data-value="initial">initial</li>
    <li data-value="tags">tags</li>
</ul>

Where each li item has a custom data attribute. On JQuery how would get all of the values of each li element which has an attribute of data-value? I want to get their value.

but this code of mine doesn't seem to be working

        $('#view-tags').click(function(){
            $('li[data-value]').each(function(){
                alert($(this).data("value"));
            })
    });

The whole code on jsfiddle: http://jsfiddle.net/Zn3JA/


回答1:


You are pretty close. You can use jQuery's .data() method to read attributes that start with data-. So in your case .data("value") since your attribute is data-value="some".

This should do it:

$('li[data-value]').each(function(){
     alert($(this).data("value"));
});

Here is a working fiddle as well: http://jsfiddle.net/nuphP/




回答2:


$(this).attr('data-value') 

should also work.




回答3:


You can use in your case:

 jQuery(this).data("value");

in order to retrieve the value.




回答4:


$(this) refers to the current li element hence you get the element alerted.

You can try what the others have suggested i.e $(this).data("value")




回答5:


   $('#view-tags').click(function(){
        $('li[data-value]').each(function(){
        var value = $(this).attr('data-value');
            alert(value);
        })
}); // this work normally

Takes the attribute value and stores the variable value

var value = $ (this) .attr ('date value');

After this warning the variable value

alert (value);


来源:https://stackoverflow.com/questions/11759358/selecting-custom-data-attributes-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!