I have this elements on my site which are added dynamically on jQuery's document.ready
function.
The problem is that I can't select those element using regular jQuery selectors. The JavaScript runs fine in IE9 and other browsers. I think the reason why it does not work is because the content that I'm trying to alter is added dynamically.
H开发者_运维技巧ow do I solve this issue?
Code:
$('.dynamic').each(function(index)
{
$('textarea, input[type=radio], input[type=checkbox], select, input[type=text]', this).each(function()
{
var array = $(this).val().split('|||');
var elements = new Array();
var target = String('.dynamic_'+$(this).attr('id'));
$(target).each(function() //this does nothing in ie7 and 8, seems the target selector is messed up :S
{
elements.push($(this));
});
for (val in array)
{
var count = Number(val);
$(elements[count]).val(array[val]);
}
});
});
I don't see any specific reason for targeting a javascript to IE7 or IE8 since we are all talking about jQuery here. I believe the real problem is not related to the browser itself, it's the misuse of event bindings.
You have to use the live()
or delegate()
method. They both will assign the event to the already existing elements in DOM and to the elements created dynamically.
Ex:
$(".element").live("click", function() {
//dazzling stuff here
});
And with delegate:
$('.element').delegate('.context-element', 'click', function() {
//dazzling stuff here
});
I suggest you to use deletage()
instead of live()
since I already experienced many bugs related to event bubbling in some browsers while using live. Also delegate()
is much faster too, so if you're working on a very intense application in terms of DOM manipulation, better to use it.
Use On()
instead of Live()
if possible.
http://www.jquery4u.com/jquery-functions/on-vs-live-review/#.UH24mGmopTg
You need to use live() for elements added at runtime: http://api.jquery.com/live/
If you are trying to select the element after adding them dynamically inside document.ready
then it should work fine. If you are trying to select element when it doesn't exist and trying to attach event handlers then you should go for live
.
精彩评论