m9_*_*psy 1 html javascript jquery
我试图在我的HTML中使用自定义"selected"属性,jQuery总是返回此属性的错误值.我知道,"selected"在options标签中使用,但为什么我不能在其他标签中使用它?只看例子:http://jsfiddle.net/SE7FB/8/
<div class="category" selected="false">First</div>
<div class="category" selected="false">Second</div>
<div id="tester" style="width: 100px; height: 100px; float: right; background-color: black;"></div>
Run Code Online (Sandbox Code Playgroud)
JavaScript的:
$(".category").click(function () {
$("#tester").css("background-color", "rgb(" + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + ")");
$("#tester").append("<p>" + $(this).attr("selected") + "</p>");
if ($(this).attr("selected") == "true") {
$(this).css("background-color", "transparent");
$(this).attr("selected", "false");
} else if ($(this).attr("selected") == "false") {
$(this).css("background-color", "blue");
$(this).attr("selected", "true");
}
});
Run Code Online (Sandbox Code Playgroud)
为什么我不能在其他标签中使用它?
因为它不是有效的HTML.然后,浏览器会出现意外行为.
如果要使用自定义属性,请使用以下属性data-*:
<div class="category" data-selected="false">First</div>
$(".category").data('selected'); // get
$(".category").data('selected', value); // set
Run Code Online (Sandbox Code Playgroud)
链接: