Reputation: 3401
I'm a freshman to jQuery. I think it's reasonable that jQuery could manipulate elements added by code, but I found it couldn't just now.
$(function(){
$("#addVideo").click(function(){
$("#publisher").append("<div id='choseType'><input type='button' value='video'> <input value='music' type='button'> <input type='button' value='X'></div>");
})
$("#choseType input:eq(0)").click(function(){
$(this).addClass("selected");
})
})
Is it jquery's limitation or my code's fault? It seems if I put the second click()
function into the first one it will run correctly, but it will only run once(if I remove the appended #choseType
and append it again the second click won't work.).Then how do I manipulate code added elements? Thanks!
Upvotes: 2
Views: 1227
Reputation: 119867
$(function(){
$("#addVideo").click(function(){
//create new content, and append to publisher
//also, reference the new content
var newContent = $("<div><input type='button' value='video'> <input value='music' type='button'> <input type='button' value='X'></div>").appendTo('#publisher');
//then add a handler to input in the context of the new content
$("input:eq(0)", newContent).click(function(){
$(this).addClass("selected");
});
})
})
Upvotes: 2
Reputation: 318312
Delegate the event to an element that is not dynamic:
$(document).on('click', "#choseType input:eq(0)", function(){
$(this).addClass("selected");
});
And ID's are unique!
Upvotes: 4