javaScript不适用于由jquery加载函数加载的页面

时间:2013-01-28 19:23:52

标签: javascript jquery html

Page 1

<html>
<head>
<script src="jquery-1.8.3.js" type="text/javascript"></script>
</head></head>
<body><div id="main"></div> </body>
<script>$('div[id=main]').load('page2.php')
$('span[id*=temp]').on('click',function(){
alert(this.id); }); //this block of code not working!!
</script>
</html>

第2页

<div>
<span id="temp">
this is demo
</span>
</div>

基本上我想在点击标签时在主div中再次加载page2但是我无法在第一页中获取标签的id,第1页的脚本不适用于第2页的项目或标签

2 个答案:

答案 0 :(得分:1)

您正在尝试在AJAX调用之后立即绑定事件,因此该元素尚不存在。该调用是异步的,因此它不会停止代码执行以等待响应。

使用success方法的load回调,在内容加载后绑定元素:

$('div#main').load('page2.php', function(){
  $('span[id*=temp]').on('click', function(){
    alert(this.id);
  });
});

或使用委托将事件绑定到父元素:

$('div#main').load('page2.php');
$('div#main').on('click', 'span[id*=temp]', function(){
  alert(this.id);
});

答案 1 :(得分:0)

因为您需要指定父选择器以考虑动态创建的元素。

例如:

$("#main").on('click', 'span[id*="temp"]', function() {alert('Handler is working!');})

以下是一个很好的相关问题:jQuery 1.7 on() and off() methods for dynamic elements

相关问题