I set the class of an element, and now I want to change the class of the element through JavaScript. I tried jQuery's attr to modify the class attribute, but it didn't work.
html:
<nav>
<ul class="pager" id="pageCtr">
<li class="previous" id="prevBTN">
<a href="#" onclick="prevPage()"><span>←</span>前一页</a>
</li>
</ul>
</nav>
js:
$('#prevBTN').className='previous disabled';
某草草2017-05-18 10:49:55
Hypothetical elements
<p class="className" id="idValue"></p>
You can change it like this
var e = document.getElementById('idValue')
if (e) {
e.className = "changedClassName"
}
Tried and tested.
jQuery just document.getElementById('idValue')
改成$('#idValue')
and it’s ready
黄舟2017-05-18 10:49:55
HTML:
<p id="id_test" class="old-bootstrap">
JS:
$('#id_test').className='new_class';
not passattr
,而是通过className
PS:
If you want to add the attribute disabled
to li
, you can do this, instead of adding class
but attr
:li
添加属性disabled
可以这样做,不是添加class
而是attr
:$('#prevBTN').attr('disabled', true);
$('#prevBTN').attr('disabled', true);
Remove attr:
Option 1: The a tag does not support the disabled attribute, so you can just replace the a tag with the button tag: http://www.w3school.com.cn/ti...
Option 2: Use The a tag can also be used. By removing its href attribute, you can achieve a non-clickable effect, that is,$('#prevBTN').removeAttr('href');
Reference: You take the following code and run it on this
<!DOCTYPE html>
<html>
<head>
<script src="/jquery/jquery-1.11.1.min.js"></script>
<script>
function test() {
$('#id_test').removeAttr('href');
}
</script>
</head>
<body>
<nav>
<ul class="pager" id="pageCtr">
<li class="previous" id="prevBTN">
<a href="#" id="id_test" onclick="prevPage()"><span>←</span>前一页</a>
</li>
</ul>
</nav>
<button id="id_test2" onClick="test()">disable</button>
</body>
</html>
怪我咯2017-05-18 10:49:55
What is the code of the original poster?
Why is it okay for me to directly use attr() to set the class?
In addition, jQuery also has two methods: addClass() and removeClass. I generally use these two methods to operate classes.
黄舟2017-05-18 10:49:55
jQuery has special methods for operating classes, you can check the relevant API
淡淡烟草味2017-05-18 10:49:55
Thanks to @daryl and @tony_yin for their enthusiastic answers. I want to use it myself <li>
标签里面的 <a>
换成 <button>
,能实现禁用按钮效果,但是 .pager
的 BootStrap 默认样式会变化;
将<li class="previous" id='prevBTN'>
换成 <li class="previous disabled" id='prevBTN'>
使用 document.getElementById('prevBTN').className='previous disabled';
确实可行,但使用 jQuery 时会出现问题,$('prevBTN').className='previous disabled';
就不能实现,主要原因是 $('prevBTN')
并不能得到 DOM 元素,而 className 是 DOM 里面的属性,$(selector)
I can only get a collection of DOM elements that meet the selector conditions,
jQuery() (or $()) with an id selector as its argument will return a jQuery object containing a collection of either zero or one DOM element.
Solution:$('prevBTN').get(0).className='previous disabled';