开发者

jQuery dynamic element is created but not able to get the handle to dynamic elements

开发者 https://www.devze.com 2023-01-19 09:49 出处:网络
In the below code, I am looping through each XML and creating dynamic content. $(\'#instDiv\').append( \"<div><b>\" +

In the below code, I am looping through each XML and creating dynamic content.

$('#instDiv').append( "<div><b>" + 
$(this).attr('institute') + "</b></div>" + 
"<div>Type: " + $(this).find('type').text() + 
"</div>" + "<div>Name:</div>" + 
"<div onClick=\"showDiv('inst"+idCounter+"');\"><b>" + $(this).find('RM').text() + 
"</b></div>" + "<span id=\"inst"+idCounter+"\" >" + 
"<table><tr><td rowspan=3><img height=50 width=40 src='imgurl'></img></td><td>Phone#: " + $(this).find('ph').text() + "</td></tr>" + 
"<tr><td>Email: " + $(this).find('mail').text() + 
"</td></tr>" + "<tr><td开发者_开发百科>Location: " + $(this).find('loc').text() + 
"</td></tr></table></span>" );

Calling a showDiv function on click of the name. Creating a span with id as inst & counter.

So for the first element, the id would be inst0.

The showDiv function code is shown below.

function showDiv(divID) {
 alert(divID);
 alert($('#instDiv').html());
 alert($(divID).length);
 $(divID).toggle(); 
}

In the above code, I am able to get the divID value & innerHTML of instDiv also printing the span with the same id.

But, when I try to print that divID length, its returning 0. Which means, there is no element with that id. In our example the id is inst0. But, this is present in instDiv innerHTML.

How can I get the access to that element. I need to toggle the display on click of the name.


The jQuery selector should be #inst0 rather than just inst0 if you are selecting by the ID attribute, so prepend a hash/pound symbol like this:

function showDiv(divID) {
   alert($('#' + divID).length);
   $('#' + divID).toggle(); 
}
0

精彩评论

暂无评论...
验证码 换一张
取 消