好家伙 我想添加一个单击事件是通过AJAX从服务器返回的元素。很显然,我必须附上我的js文件里面我得到的回答,而不是我的主要脚本。这是最好的做法呢?我一定要创建分离的js文件就返回文本??
Hello guys I am trying to add a click event on the element that is return from the server via ajax. Apparently, I have to attached my js file inside my return response instead of my main script. Is this the best practice? Do I have to create the separated js file to add event on the return text??
例如:
我的jQuery的 - selectWeek.js
My Jquery - selectWeek.js
$(document).ready(function(){
//handle ajax..
var url="sendSchedule.php";
$.post(
url,
{week:input},
function(responseText){
$("#ajax").html(responseText);
},
"html"
);
// click on #add button
$("#add").click(function(){
//do something
return false;
});
});
我的主页
<script type="text/javascript" src="JS/selectWeek.js"></script>
</HEAD>
<BODY>
//the code that trigger ajax is omitted
<div id=ajax>
//the response text will be inserted here
</div>
</BODY>
</HTML>
来自服务器的响应
response from the server
// display html (omit)
// Do I have to attach the same js file to let #add listen the event?
<script type="text/javascript" src="JS/selectWeek.js"></script>
<form>
<input type='button' id='add' value='add'/>
</form>
我不知道如果我做我的问题清楚。我想知道如果我需要在返回文本添加事件。我一定要添加在返回文本的js文件链接或者是有办法做到这一点的主页上。我只想写我的js code中的主页上,并保持它的简单。感谢您的任何答复。
I am not sure if i make my question clear. I want to know if I need to add events on the return text. Do I have to add js file link on the return text or there is a way to do it on the main page. I just want to write my js code on the main page and keep it simple. Thanks for any reply.
尝试 jQuery的现场活动的。这些事件使您可以为事件添加新元素附加到DOM。比如我跑我的页面,这个页面调用一个ajax GET / POST中插入ID为mydiv到DOM一个div。我的现场活动将钩到新添加的格。 这样,您就可以将所有必要的JavaScript单个页面的一个库。检查出来它是非常有用的。
Try jquery live events. These events allow you to attach events to the dom as new elements are added. For instance I run my page and this page calls an ajax get/post that inserts a div with id "mydiv" to the dom. My live event will hook to the newly added div. This way you can keep all the necessary javascript for a single page in one library. Check it out it is very useful.