1

我遇到了类似的问题:JavaScript not working inside AJAX loaded DIV但我的问题是我没有任何要绑定的事件。我有这个:

$('[title]').colorTip({color:'yellow'});

将所有具有 'title' 属性的元素绑定到该对象。它在页面重新加载时工作正常。但在来自 AJAX 调用的元素上,故事有所不同,它显示为 javascript 不存在。我知道使用 AJAX 将元素绑定到其他事件live(),但是如何绑定没有“事件”的元素?

4

2 回答 2

9

您必须在 ajax 调用后重新绑定工具提示。

$( document ).ajaxStop( function() {
    $('[title]').colorTip({color:'yellow'});
});

或者按照 jbabey 的建议,您可以使用完整的回调来重新绑定工具提示(此处的简化版本):

$(
function(){
    // Get a reference to the content div (into which we will load content).
    var jContent = $( "#content" );             
    // Hook up link click events to load content.
    $( "a" ).click(
        function( objEvent ){
            var jLink = $( this );
            // Clear status list.
            $( "#ajax-status" ).empty();
            // Launch AJAX request.
            $.ajax(
                {
                    // The link we are accessing.
                    url: jLink.attr( "href" ),
                    // The type of request.
                    type: "get",
                    // The type of data that is getting returned.
                    dataType: "html",
                    complete: function(){
                        console.log("finalized ajax request");
                        //re-bind the tooltip
                        $('[title]').colorTip({color:'yellow'});
                    },
                    success: function( strData ){
                        console.log("ajax success");
                        console.log(strData);
                        // to something with the received data
                        jContent.html( strData );
                    }
                }                           
                );
            // Prevent default click.
            return( false );                    
        }
        );

}
);

根据您的评论,我包括以下内容:您还必须确保在页面加载时绑定工具提示:

$( document ).ready( function() {
    $('[title]').colorTip({color:'yellow'});
});
于 2013-01-31T18:10:46.057 回答
0

您可以在元素上创建更改事件。

$('title').live('change', function () {
whatever you want to do here
})

然后,只要您希望属性生效,您就可以触发更改。

$('title').trigger('change');
于 2013-01-31T18:12:41.253 回答