开发者

jquery reference an inserted div

consider:

<div id="message"></div>

The jquery says:

var html_to_insert = '<div id="mynewdiv"><input id="myfield" name="myfield" type="text" value="" /></div>'
$('#message').html(html_to_insert);

The html result is as expected:

<div id="message"><div id="mynewdiv"><input id="myfield" name="myfield" type="text" value="" /></div></div>

The problem I am having is when I call the "myfield" i开发者_运维问答t does not work:

$('#myfield').change(function(){                      
  alert("field changed");                       
});

How can I fix this?

I believe the reason that it will not call it is because the field does not exist when the page first renders, but I am not sure how to fix it.


First

$('#myfield').change(                        
  alert("field changed");                       
);

is invalid. it should be:

$('#myfield').change(function(){                      
  alert("field changed");                       
});

but if you are calling it on page load you should use live.

$('#myfield').live('change', function(){                      
  alert("field changed");                       
});


To see if the field exists do this:

alert($('#myfield').length > 0);


can also just add the event after the elem is inserted to the DOM :


$('#message').html(html_to_insert, function () {
  $('#myfield').change(function(){                      
    alert("field changed");                       
  });
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜