最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery can't access append element - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question edited Jan 8, 2013 at 3:46 icktoofay 129k23 gold badges258 silver badges236 bronze badges asked Jan 8, 2013 at 3:43 OscarOscar 491 silver badge7 bronze badges 0
Add a comment  | 

5 Answers 5

Reset to default 7

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");
  });
});

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);

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

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
});

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");
  });
});
发布评论

评论列表(0)

  1. 暂无评论