我有基于div的下拉列表,其值存储在TD [数据值]中。我想在TD数据值发生变化时编写脚本。 低于td的格式:
<td data-value="some-id">
<div class="dropdown">some elements</div>
</td>
我试试
$("table tr td:eq(1)[data-value]").change(function(){
//
}
但没有工作
答案 0 :(得分:0)
change
事件处理程序仅适用于输入元素。你可以这样做:
if($("table tr td:eq(1)[data-value]") != 'some-id'){
console.log('changed');
}
什么时候会改变价值?也许你这样做:
$("table tr td:eq(1)[data-value]").click(function(){
$(this).data('value') == 'some-id' ? 'other-value' : 'some-id';
//here you may do other stuff as above...
});
答案 1 :(得分:0)
更改事件应直接绑定到值已更改的div
<table>
<tr>
<td data-value="some-id">
<div>some elements</div>
</td>
</tr>
</table>
$("table > tbody > tr > td[data-value='some-id'] > div").change(function(){
//changed
alert();
});
$('div').trigger("change");
答案 2 :(得分:0)
您可以在现代浏览器中使用MutationObservers
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.attributeName = 'data-value') {
snippet.log('value of ' + mutation.target.id + ' changed to: ' + $(mutation.target).attr('data-value'))
}
});
});
var config = {
attributes: true
};
$('td[data-value]').each(function() {
observer.observe(this, config);
});
//to test
$('input').change(function() {
$('td[data-value]').eq($(this).data('index')).attr('data-value', this.value)
})
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<td data-value="some-id" id="1">
<div class="dropdown">some elements</div>
</td>
</tr>
<tr>
<td data-value="some-id" id="2">
<div class="dropdown">some elements</div>
</td>
</tr>
</table>
<!--to change the value of attribute change the input value-->
<input data-index="0" />
<input data-index="1" />