$('.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为999
,inptest
为999
现在将sela
更改回ADMIN
并再次更改为AUTH
我希望它保持999
,但它会变为right
如何在sela
选项上保留更改后的数据值?
答案 0 :(得分:3)
保持一致,
使用.attr('data-x')
/ .attr('data-x', newValue)
或使用.data('x')
/ .data('x',newValue)
所以
$('.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;
或者
$('.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;