jQuery- 检测 SPAN 字段内容的变化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31000425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery- Detect change in the content of a SPAN field
提问by IGGt
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>
I need to know when the content changes, e.g. I click on it, and change it from 0 to 1.
我需要知道内容何时发生变化,例如我单击它,然后将其从 0 更改为 1。
I tried:
我试过:
$(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
) is used because on my main page, the initial field is loaded dynamically)
(nb $(document.body
) 的使用是因为在我的主页上,初始字段是动态加载的)
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).
我猜这是它不喜欢的“改变”,但看不出用什么来代替它。(jQuery / HTML5 很好,因为它只在内部使用)。
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.
我看过一些例子,但它们通常似乎适用于更复杂的场景,需要多个函数来检测发生某些其他事情时的变化,但我认为必须有一个类似于该on change
方法的更简单的解决方案。
回答by Praveen Kumar Purushothaman
You can use this event DOMSubtreeModified
:
您可以使用此事件DOMSubtreeModified
:
$("span").on('DOMSubtreeModified', function () {
alert("Span HTML is now " + $(this).html());
});
Snippet
片段
$(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>
回答by Ankit Kathiriya
i think this code will help you.
我认为这段代码会帮助你。
$(document).ready( function() {
$('#myId').bind( "contentchange", function(){
alert("Changed");
});
$( "#btn" ).click( function () {
$('#myId').html( "Value" ).trigger( "contentchange" );
});
});