如何更改自己定义的属性

时间:2013-11-07 20:21:57

标签: javascript jquery html html5

我想知道如何使用JavaScript / jQuery在html标签中更改自己定义的属性。 例如: 我已经定义了名为升序的属性:

<th ascending="true" id="1">some text</th>

在JavaScript / jQuery中我想在“false”上更改该属性 我正在尝试这种方式,但它不起作用(我想这个选项仅适用于预定义的属性):

var tag = document.getElementById("1");
    tag.ascending = "false";

3 个答案:

答案 0 :(得分:2)

添加自定义时使用自定义data-*属性,否则它不会通过验证!在你的情况下:

<th data-ascending="true" id="1">some text</th>

获取/设置(纯JS):

var tag = document.getElementById("1");
tag.getAttribute("data-ascending"); //get
tag.setAttribute("data-ascending", true); //set

jQuery的:

$("#1").data("ascending"); //get
$("#1").data("ascending", true); //set

答案 1 :(得分:1)

您可以使用“setAttribute”方法。

像这样:tag.setAttribute(“升序”,“假”);

答案 2 :(得分:0)

在jquery中尝试这个

$(function(){
  $('#1').attr('ascending',false);
});

但你应该使用.prop()

$(function(){
  $('#1').prop('ascending',false);
})

或在javascript中

function changeValue() {
  var tag = getElemendById('1');
  tag.setAttribute('ascending', false);
}

和javascript版本的html应如下所示:

<th onLoad="changeValue()" data-ascending="true" id="1">some text</th>

我没有测试它但它应该工作;)

相关问题