jQuery-检测SPAN字段内容的变化 [英] jQuery- Detect change in the content of a SPAN field
问题描述
我有以下代码用于模拟文本框:
I have the below piece of code which is used to simulate a text box:
<label for="alertCmpVal">ALERT VALUE:</label>
<span class="center textBox displayField highlight" id="alertCmpVal" contenteditable> <?php print $alert_val;?> </span>
我需要知道内容何时更改,例如我单击它,并将其从0更改为1.
I need to know when the content changes, e.g. I click on it, and change it from 0 to 1.
我尝试过:
$(document).ready(function()
{
$(document.body).on('change','#alertCmpVal',function()
{
alert("boo");
$('#alertCmpVal').removeClass('highlight');
})
}
但是这似乎不起作用.
but this doesn't seem to work.
(n.b.$(document.body
)是因为在我的主页上,初始字段是动态加载的)
(n.b. $(document.body
) is used because on my main page, the initial field is loaded dynamically)
我猜想它是它不喜欢的改变",但是看不到用什么来代替它. (jQuery/HTML5很好,因为它仅在内部使用).
I'm guessing it is the 'change' that it doesn't like, but can't see what to replace it with. (jQuery / HTML5 is fine, as it is only used internally).
我已经看到了一些示例,但是它们似乎通常用于更复杂的场景,当某些其他事情发生时,它们需要多个功能来检测更改,但是我认为必须有一个类似于on change
的更简单的解决方案方法.
I've seen a few examples, but they generally seem to be for more complex scenarios, requiring multiple functions to detect the change when certain other things occur, but I figure there must be a simpler solution similar to the on change
method.
推荐答案
您可以使用此事件DOMSubtreeModified
:
$("span").on('DOMSubtreeModified', function () {
alert("Span HTML is now " + $(this).html());
});
代码段
$(function () {
$("a").click(function () {
$("span").html("Hello, World!");
});
$("body").on('DOMSubtreeModified', "span", function () {
alert("Span HTML is now " + $(this).html());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<span>Hello</span>
<a href="#">Click</a>
这篇关于jQuery-检测SPAN字段内容的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!