当div值改变时执行javascript函数

时间:2013-12-05 09:32:46

标签: javascript jquery html

我有一个div <div id="Country">India</div>。我想在div值改变时执行一些代码(比如JavaScript函数)。我怎样才能听取div值的变化?我需要使用Jquery吗?

5 个答案:

答案 0 :(得分:4)

一个简单的jquery解决方案是使用自定义事件并在更改DOM时自行触发:

$("#country").html('Germany').trigger('CountryChanged');


$('#country').on('CountryChanged', function(event, data) {
   //contentchanged
});

答案 1 :(得分:2)

我为你准备了一个小型演示。它有点粗糙,但我相信你可以改进它;)。

快乐编码:)

<!DOCTYPE html>
<html>

    <head>
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    <script>


    $(document).ready(function(){

    $("#ChangeText").click(function(){
        var value = $("#DivText").val();
        $("#Country").text(value);
    });

    $('#Country').bind('DOMNodeInserted DOMNodeRemoved', function(event) {
    if (event.type == 'DOMNodeInserted') {
        alert('Content added! Current content:' + '\n\n' + this.innerHTML);
    } else {
        alert('Content removed! Current content:' + '\n\n' + this.innerHTML);
    }
    });
});
    </script>
    </head>

    <body >
    <input type="text" id="DivText" />
    <button id="ChangeText"> Change Div Text </button> <br /> <br />
        <div id="Country">India</div>   

    </body>
</html>

答案 2 :(得分:0)

您可以收听MutationObserver DOM API触发的事件: https://developer.mozilla.org/en/docs/Web/API/MutationObserver

答案 3 :(得分:0)

试试这个演示,它位于Cracker0dks的链接http://jsbin.com/ayiku中,这是代码http://jsbin.com/ayiku/1/edit

答案 4 :(得分:0)

在脚本标记中尝试:

$(document).ready(function(){

var new_country1 = "";
var new_country2 = "";
var func_flag = 0;
    $('#Country').bind('DOMNodeInserted DOMNodeRemoved', function(event) {      

    if (event.type == 'DOMNodeInserted') {
        new_country1 = this.innerHTML;  
        if(new_country1 != new_country2 && func_flag == 1) {
            country_changed_function();
        }                   
    } else {
        new_country2 = this.innerHTML;
    }

    func_flag = 1;  

    });
});

function country_changed_function(){
    alert('country changed.');
}

这里“country_changed_function”是国家div innerHTML上的功能触发器。

相关问题