[英]How to update the value of data attribute using jquery
I have the following bootstrap data toggle markup and I want to change the icon and the text to change on toggle. 我有以下引导数据切换标记,并且我想更改图标和文本以在切换时更改。 I can get the text to change but not the icon.
我可以更改文本,但不能更改图标。 What I'm I doing wrong?
我做错了什么?
<div id="collapseDiv" >
<dl>
<dt>...</dt>
<dd>...</dd>
</dl>
</div>
<a href="#collapseDiv" data-toggle="collapse" class="icon-before" data-icon="">Show More</a>
Jquery code is as follows jQuery代码如下
$('#collapseDiv').on('shown.bs.collapse', function () {
$('.icon-before').data('icon', '').text('Show Less');
});
$('#collapseDiv').on('hidden.bs.collapse', function () {
$('.icon-before').data('icon', '').text('Show More');
});
Try using attr()
尝试使用
attr()
attr('data-icon', '')
Also check this excellent answer 同时检查这个很好的答案
EXPLANATION 说明
Check the following example. 检查以下示例。
If you click on span#one
the attribute changes with attr()
function, if you click on span#two
we will try to change the attribute with data()
function. 如果单击
span#one
则属性将通过attr()
函数更改,如果单击span#two
我们将尝试使用data()
函数更改属性。
When you try to select the element with [data-test="false"]
only the first element has changes it's data attribute. 当您尝试使用
[data-test="false"]
选择元素时,只有第一个元素的data属性有所更改。
Only the element with data-test="false"
will get red: 仅具有
data-test="false"
的元素将变为红色:
$(document).on('click', 'span', function() { var that = $(this); var id = that.attr('id'); if (id == 'one') { //Try with attr() that.attr('data-test', 'false'); } else if (id == 'two') { //Try with data() that.data('test', 'false'); } $('[data-test="false"]').css({'color':'red'}); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <span id="one" data-test="true">one</span> <span id="two" data-test="true">two</span>
You should update the attribute value, rather than updating data property: 您应该更新属性值,而不是更新数据属性:
$('#collapseDiv').on('shown.bs.collapse', function () {
$('.icon-before').attr('data-icon', '').text('Show Less');
});
$('#collapseDiv').on('hidden.bs.collapse', function () {
$('.icon-before').attr('data-icon', '').text('Show More');
});
You should also update class of .ui-icon inside. 您还应该在其中更新.ui-icon的类。
var oldIcon = $('.icon-before').data('icon'),
newIcon = '';
uiIcon = $('.icon-before').data('icon', newIcon).find('.ui-icon');
uiIcon.removeClass('ui-icon-' + oldIcon).addClass('ui-icon-' + newIcon);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.