Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

html - JQuery data selector not updating with .data

Basically if I have a div loaded onto a page with a data-test attribute and change the value of it with jquery's .data('test') I can no longer select the element with $('div[data-test="newValue"]')

var howMany = $('.t[data-test="test"]').length;
$('.result').html('start there are ' + howMany + ' divs with data "test"<br /><br />');
setTimeout(function() {
  $('#one, #three').data('test', 'changed');
}, 500);
setTimeout(function() {
  var test = $('.t[data-test="test"]').length,
    changed = $('.t[data-test="changed"]').length;
  $('.result').append('there are ' + test + ' divs still with data "test"<br /><br />there are ' + changed + ' divs still with data "changed"<br /><br />');
}, 1000);
setTimeout(function() {
  $('.t').each(function() {
    $('.result').append('div #' + $(this).attr('id') + ' has the test data of: ' + $(this).data('test') + '<br /><br />');
  });
}, 1500);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="t" id="one" data-test="test">1</div>
<div class="t" id="two" data-test="test">2</div>
<div class="t" id="three" data-test="test">3</div>
<div class="t" id="four" data-test="test">4</div>
<div class="result"></div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

jQuery .data() is initially populated with values from the data- attributes, but setting it only stores the associated new value in memory. It doesn't change the attribute in the DOM. To change the attribute, you have to use:

$('#one, #three').attr('data-test', 'changed');

The docs are at http://api.jquery.com/jQuery.data/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...