最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Change HTML attribute with jQuery - Stack Overflow

programmeradmin4浏览0评论

I am using jQuery 1.4.4. and I have this source code:

<div id="area1">
    <ul id="testlist" data-filter="false">

    </ul>
</div>

How can I change the data-filter attribute to true in jQuery? I tried for example:

$('#testlist').attr("data-filter").val(true);

but it does not work.

Anyone an idea?

Best Regards.

I am using jQuery 1.4.4. and I have this source code:

<div id="area1">
    <ul id="testlist" data-filter="false">

    </ul>
</div>

How can I change the data-filter attribute to true in jQuery? I tried for example:

$('#testlist').attr("data-filter").val(true);

but it does not work.

Anyone an idea?

Best Regards.

Share Improve this question asked Dec 13, 2010 at 15:48 TimTim 13.3k36 gold badges111 silver badges159 bronze badges 0
Add a comment  | 

8 Answers 8

Reset to default 8

The syntax for attr is $.attr(attributeName, value);. Try this:

$('#testlist').attr("data-filter", true);

Since you're using jQuery 1.4.4 and "data" attributes, you can use jQuery's .data() method:

Example: http://jsfiddle.net/patrick_dw/SLskn/

alert( $('#testlist').data("filter") ); // alerts "false"

$('#testlist').data("filter",true);

alert( $('#testlist').data("filter") ); // alerts "true"

From the docs:

As of jQuery 1.4.3 HTML 5 data- attributes will be automatically pulled in to jQuery's data object.

You're using the wrong syntax. Try this:

$('#testlist').attr("data-filter", true);

Try this:

$('#testlist').attr("data-filter", "true");

Or possibly

$('#testlist').attr("data-filter", true);

$('#testlist').attr("data-filter",true);

http://api.jquery.com/attr/

Try $('#testlist').attr("data-filter", "true"); instead

The correct usage of .attr is .attr(name, value)

So change your code to

$('#testlist').attr("data-filter", true);

http://api.jquery.com/attr/

So you're using the HTML5 syntax for custom attributes... Nice.

There is a jQuery metadata plugin that allows you to access those attributes in a more semantic way. Just use it like this:

// Reading:
var tooltipTitle = $(".tooltip").metadata().filter;

// Writing:
$(".tooltip").metadata().filter = "whatever";
发布评论

评论列表(0)

  1. 暂无评论