1

我在页面上有几个单选按钮和 span 元素。当我单击某个单选按钮时,Onchange 事件处理程序会触发并更改 span 元素的文本。我无权访问该事件处理程序,因此无法更改它。我需要编写自己的脚本(Onchage 事件处理程序),这将在其他脚本之后更改 span 元素的文本,如上所述,更改 DOM 中的 span 元素。示例:HTML:

<div>
<input type="radio" name="somename" value="1.232" checked="checked">1.232
<input type="radio" name="somename" value="2.556">2.556
<input type="radio" name="somename" value="3.232">3.232
<input type="radio" name="somename" value="4.865">4.865
</div>
<span id="change">1.232</span>

Javascript:

$('div input:radio').change(function(){
    //some logic here
    //calculation of value of the varaiable 'new_value' is encapsulated
    //new_value = .....
    $(#change).html(new_value);
});

我无法更改上面的 javascript 代码。我需要编写 onChange 事件处理程序来更改跨度的 html 取决于上面的脚本制作的新值。如果我只写:

$('div input:radio').change(function(){
    alert($(#change).html());
});

我会提醒老跨度的值。如何实施?

4

1 回答 1

1

好的,所以问题是调用.html()实际上并没有触发事件(人们可能希望在这种情况下调用更改事件),所以你必须扩展 jQuery(实际上并不难)所以你可以听一些你可以听的东西试试这个:(演示

(function ($) {
    // create a reference to the old `.html()` function
    var htmlOriginal = $.fn.html;

    // redefine the `.html()` function to trigger an event
    $.fn.html = function (html) {
        var ret = htmlOriginal.apply(this, arguments);
        //if ret is a String then there is no event to trigger
        if(typeof ret !== "string") {
            ret.trigger('html-change');
        }
        return ret;
    }
})(jQuery);

$(function () {
    $('div input:radio').change(function () {
        var v = $(this).val();
        //Original and magical value
        setTimeout(function () {
            //Just doing some async stuff to prove that these are decoupled
            $('#change').html(v);
        }, 500);
    });

    $('#change').on('html-change', function () {
        //Now just listen to the html-change event which will be triggered any time .html() is called even that call was made by previously unmodified code)
        alert($(this).html());
    });
});
于 2013-11-14T20:54:37.880 回答