jQuery- Detect change in the content of a SPAN field

廉价感情. 提交于 2019-11-30 07:10:42

问题


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.

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)

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).

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.


回答1:


You can use this event 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>



回答2:


i think this code will help you.

$(document).ready( function() {
    $('#myId').bind( "contentchange", function(){
        alert("Changed");
    });

    $( "#btn" ).click( function () {
        $('#myId').html( "Value" ).trigger( "contentchange" );
    });
});

http://jsfiddle.net/RKLmA/192/



来源:https://stackoverflow.com/questions/31000425/jquery-detect-change-in-the-content-of-a-span-field

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!