jQuery can't access append element

天大地大妈咪最大 提交于 2019-12-10 10:39:39

问题


I have this inside a function:

$('#users').append($("<div id='usuarios'>").text(mensaje[1][i]));

I want to create an onclick event for this new <div>. How can I achieve this? I'm trying it like this outside the function:

$(document).ready(function(){
$('#usuarios').click(function() {
        alert("click");
    });
});

But it doesn't work.


回答1:


For jQuery 1.7+ you can attach an event handler to a parent element using .on()

$(document).ready(function(){
  $('body').on('click', '#usuarios', function() {
     alert("click");
  });
});

or Even better:

$(document).ready(function(){
  $('#users').on('click', '#usuarios', function() {
     alert("click");
  });
});



回答2:


You could do it inline (by chaining .append after .text), because that's just how jQuery's API works, but you could also put it in a variable, which looks better:

var usarios = $("<div id='usuarios'>").text(mensaje[1][i]);

usarios.click(function() {
    alert('click');
});

$('#users').append(usarios);



回答3:


I've also faced this problem, if you put it inside the document.ready then it won't work. I've thought it was my syntax, but it's not.

Use the

$(document).on('click', "input[id^='radiobox']", function () { 
    alert('hihi'); 
});

then it works




回答4:


Two ways

1.Jquery 1.7+

$(document).ready(function(){
  $('body').on('click', '#usuarios', function() {
     alert("click");
  });
});

2.Jquery<1.7

$(document).ready(function(){
  $('body').delegate('#usuarios','click', function() {
     alert("click");
  });
});



回答5:


You are dynamically creating an element, so normal event handler won't work. You will have to use on() to attach event handler to your document.

$(document).on('click', "#usuarios", function() {
    // do your job here
});


来源:https://stackoverflow.com/questions/14207883/jquery-cant-access-append-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!