weixin_33725722 2010-05-25 02:37 采纳率: 0%
浏览 39

jQuery和Ajax Post问题

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??

Example:

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;
    });
});

My main page

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

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.

  • 写回答

2条回答 默认 最新

  • weixin_33712881 2010-05-25 02:39
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘