当前位置: 动力学知识库 > 问答 > 编程问答 >

asp classic - jQuery multiple click events on dynamic elements not working

问题描述:

I would first like to say that I spend the entire day looking up the answer to this question and could not find it anywhere. I hope someone can help me here. I am not experienced with jQuery at all and so please be patient with me. :)

I have created code in classic ASP which generates a dynamic table of data which is pulled from a database. I want to be able to click on a DIV in the table and have it hide the data and show an input field. I wrote code which does this but it only does it for the first result which appears and does not work for the rest. The CLASS names are unique and so are the ID's but still doesnt allow the jQuery click event to function on the 2nd, 3rd, 4th etc rows.

This is the jQuery code I have:

<script>

$(document).ready(function(){

var taskId = $("div[class*='hide']").attr("id");

var edittaskId = $("div[class*='show']").attr("id");

$("#" + taskId).click(function(){

$("#" + taskId).hide();

$("#" + edittaskId).show();

});

});

</script>

This is the HTML/ASP code I have:

 <div id="hide_<%=rs("id")%>" class="hide<%=rs("id")%>" align="right"><%=F_task_due_date%></div>

<div id="show_<%=rs("id")%>" class="show<%=rs("id")%>" style="display: none;">

<div>

<input type="text" name="edit_task_due_date" value="<%=F_task_due_date%>" />

</div>

</div>

</div>

As I said, the code above works perfectly for the first DIV but doesnt work for the other DIVS below it in the table. How do I get this jQuery code to allow me to click on any of the other DIV elements, which match the response in the jQuery code, and also have them hide/show?

Thank you in advance.

网友答案:

If you try to get a value, such as an attribute or text or html from a group of elements, only one value can be returned and it will be the value of the first element in the collection.

Instead you need to handle the values on a per instance case within your event handlers. It is rarely necessary or beneficial to use unique identifiers within class.

If you were to remove the id portion of show and hide class you can simply do something like

$('.hide, .show').click(function(){
  /* "this" is the element clicked*/
   var taskId=this.id;
   $('#hide_'+taskId, #show_'+taskId).toggle();

});

A simpler approach that requires no ID would be:

$('.hide, .show').click(function(){      
       $(this).toggle().siblings('.hide,.show').toggle();
});
分享给朋友:
您可能感兴趣的文章:
随机阅读: