Jquery Ajax 不会绑定 Href

Jquery Ajax wont bind Href

本文关键字:绑定 Href Ajax Jquery      更新时间:2023-09-26

我通过jquery调用ajax以加载href。html 似乎加载正确。但是,加载的 html (href) 实际上不起作用。具体来说,我不知道为什么一旦通过 ajax 加载链接,当我单击它时它实际上不会做任何事情。火虫没有错误,只是死链接。我的 .on() 方法不正确吗?

首页.html

<html>
<head></head>
<body>
<div id="connections">Placeholder Text</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
var uri='home-ajax.html'; //first find out if this is created yet   
var myVar=setInterval(function(){example_ajax_request()},8000); //to do that check for it ev. 8 sec.
function example_ajax_request() {
    $.ajax({
        type: 'GET',
        url: 'home-ajax.html', //checking
        dataType: 'html', //html is content inside home-ajax.html
            success: function() {               
                $('#connections').load('home-ajax.html'); //if home-ajax exists replace connections div with its content
                clearInterval(myVar); //stop the 8 sec. timer
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                alert(thrownError);
            }
    });
}
$('myLink').on('click', function(e) { //using .on to actively bind new href link from ajax()
    document.location.href="http://www.cnn.com";//when href with id='myLink' is clicked, go to www.cnn.com
});
</script>
</body>
</html>

主场-阿贾克斯.html

<p><a href="#" id="myLink">CNN</a></p>

该元素在页面加载时不存在,因此您无法将单击函数直接绑定到它。您必须将单击委托给静态元素。

$(document).on('click', '#myLink', function(e){
    e.preventDefault(); // stop default action
    document.location.href="http://www.cnn.com"; //do work
});