如何在选择选项上保留一次更改的数据值?

时间:2018-05-02 10:52:02

标签: javascript html

$('.sela').change(function(){
  var obj = $('.sela:visible');
  var uname = obj.find(':selected').data('x');
  $('#inptest').val(uname);
})

$('#btn').click(function(){
  $('.sela:visible').find(':selected').attr('data-x', 999)
  var a = $('.sela:visible').find(':selected').attr('data-x')
  $('#inptest').val(a);
});
#btn{
  cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class='sela'>
<option value='lorem1' data-x='left'>ADMIN</option>
<option value='lorem2' data-x='right'>AUTHS</option>
</select>
<br><br>
<select class='sela'>
<option value='lorem3' data-x='up'>SKY</option>
<option value='lorem4' data-x='down'>EARTH</option>
</select>
<br><br>
<input type='text' id='inptest'value='323'>
<br><br>
<div id='btn'>BUTTON</div>

先将sela更改为AUTHS inptest成为right
点击btn - sela选定的选项数据-x为999inptest999 现在将sela更改回ADMIN并再次更改为AUTH 我希望它保持999,但它会变为right 如何在sela选项上保留更改后的数据值?

1 个答案:

答案 0 :(得分:3)

保持一致,

使用.attr('data-x') / .attr('data-x', newValue)或使用.data('x') / .data('x',newValue)

所以

&#13;
&#13;
$('.sela').change(function() {
  var obj = $('.sela:visible');
  var uname = obj.find(':selected').data('x');
  $('#inptest').val(uname);
})

$('#btn').click(function() {
  $('.sela:visible').find(':selected').data('x', 999)
  var a = $('.sela:visible').find(':selected').data('x')
  $('#inptest').val(a);
});
&#13;
#btn {
  cursor: pointer;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class='sela'>
  <option value='lorem1' data-x='left'>ADMIN</option>
  <option value='lorem2' data-x='right'>AUTHS</option>
</select>
<br><br>
<select class='sela'>
  <option value='lorem3' data-x='up'>SKY</option>
  <option value='lorem4' data-x='down'>EARTH</option>
</select>
<br><br>
<input type='text' id='inptest' value='323'>
<br><br>
<div id='btn'>BUTTON</div>
&#13;
&#13;
&#13;

或者

&#13;
&#13;
$('.sela').change(function(){
  var obj = $('.sela:visible');
  var uname = obj.find(':selected').attr('data-x');
  $('#inptest').val(uname);
})

$('#btn').click(function(){
  $('.sela:visible').find(':selected').attr('data-x', 999)
  var a = $('.sela:visible').find(':selected').attr('data-x')
  $('#inptest').val(a);
});
&#13;
#btn{
  cursor:pointer;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class='sela'>
<option value='lorem1' data-x='left'>ADMIN</option>
<option value='lorem2' data-x='right'>AUTHS</option>
</select>
<br><br>
<select class='sela'>
<option value='lorem3' data-x='up'>SKY</option>
<option value='lorem4' data-x='down'>EARTH</option>
</select>
<br><br>
<input type='text' id='inptest'value='323'>
<br><br>
<div id='btn'>BUTTON</div>
&#13;
&#13;
&#13;