在jQuery或JavaScript中是否有在span标记text/html已更改时触发的事件?
代码:
<span class="user-location"> </span>
$('.user-location').change(function () {
//Not working
});发布于 2016-08-30 17:17:59
您可以使用DOMSubtreeModified跟踪span元素上的更改,即(如果span元素的文本动态更改)。
$('.user-location').on('DOMSubtreeModified',function(){
alert('changed')
})发布于 2016-08-30 07:55:42
的简短答案是jQuery和change-Event是:NO,
此事件仅限于输入元素、textarea框和选择元素。对于选择框、复选框和单选按钮,当用户使用鼠标进行选择时,事件将立即触发,但对于其他元素类型,事件将被推迟到元素失去焦点。..。下面是一个指向文档https://api.jquery.com/change/的链接
但是--这里的MutationsObserver --指向MDN引用https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver的链接,您可以监视DOM中的变化。在您的具体案例中,有问题的span。
这里是一个简短的例子(改编自MDN参考)
在这个例子中,span变化是用一个setTimeout来模拟的。
// select the target node
var target = document.getElementById('user-location');
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.info("EVENT TRIGGERT " + mutation.target.id);
});
});
// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };
// pass in the target node, as well as the observer options
observer.observe(target, config);
// simulate the Change of the text value of span
function simulateChange(){
target.innerText = "CHANGE";
}
setTimeout(simulateChange, 2000);<span id="user-location"></span>
如果您想/必须使用jQuery,您可以这样做:
在这个例子中,我添加了第二个span,以展示它如何工作。
// Bind to the DOMSubtreeModified Event
$('.user-location').bind('DOMSubtreeModified', function(e) {
console.info("EVENT TRIGGERT " + e.target.id);
});
// simulating the Change of the text value of span
function simulateChange(){
$('.user-location').each(function(idx, element){
element.innerText = "CHANGED " + idx;
});
}
setTimeout(simulateChange, 1000);<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<span id="firstSpan" class="user-location">Unchanged 0</span><br/>
<span id="secondSpan" class="user-location">Unchanged 1</span>
发布于 2017-03-15 09:29:18
使用Javascript MutationObserver
//More Details https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
// select the target node
var target = document.querySelector('.user-location')
// create an observer instance
var observer = new MutationObserver(function(mutations) {
console.log($('.user-location').text());
});
// configuration of the observer:
var config = { childList: true};
// pass in the target node, as well as the observer options
observer.observe(target, config);https://stackoverflow.com/questions/39221775
复制相似问题