Jquery Ajax不会绑定Href

时间:2013-01-28 18:38:20

标签: javascript jquery

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

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

主-ajax.html

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

1 个答案:

答案 0 :(得分:1)

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

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