简体   繁体   中英

Change HTML attribute with jQuery

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.

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";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM