<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>代码怎样写才能找到文档装载后新建的节点?</title> <script type="text/javascript" src="./jquery-1.4.2.js"></script>
<script type="text/javascript">
//文档装载完毕后新加一个A
$(document).ready ( function () {
$("div#nihao").append("<a id=\"hello\" href=\"http://www.g.cn\">Google2</a>");
});
</script> <style type="text/css">
</style>
</head> <body>
<div id="nihao">
<a id="first" href="http://www.g.cn">Google1</a>
</div>
<script type="text/javascript">
//阻止链接跳转(失败)
$("#hello").click (function (event) {
alert("nihao");
event.preventDefault();
});
//阻止链接跳转(成功)
$("#first").click (function (event) {
alert("nihao");
event.preventDefault();
});
</script>
</body>
</html> $("#hello").click (function (event) {
alert("nihao");
event.preventDefault();
});
这段代码没起作用,显然对后加到文档中的节点无视了!
请问这是怎么回事?这个问题能解决吗?谢谢!!!
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>代码怎样写才能找到文档装载后新建的节点?</title> <script type="text/javascript" src="./jquery-1.4.2.js"></script>
<script type="text/javascript">
//文档装载完毕后新加一个A
$(document).ready ( function () {
$("div#nihao").append("<a id=\"hello\" href=\"http://www.g.cn\">Google2</a>");
});
</script> <style type="text/css">
</style>
</head> <body>
<div id="nihao">
<a id="first" href="http://www.g.cn">Google1</a>
</div>
<script type="text/javascript">
//阻止链接跳转(失败)
$("#hello").click (function (event) {
alert("nihao");
event.preventDefault();
});
//阻止链接跳转(成功)
$("#first").click (function (event) {
alert("nihao");
event.preventDefault();
});
</script>
</body>
</html> $("#hello").click (function (event) {
alert("nihao");
event.preventDefault();
});
这段代码没起作用,显然对后加到文档中的节点无视了!
请问这是怎么回事?这个问题能解决吗?谢谢!!!
function test(){
alert("nihao");
event.preventDefault();
}只能这样
也许是2、3楼说的那样吧,反正我这里是正常的
$("div#nihao").append("<a id=\"hello\" href=\"http://www.g.cn\">Google2</a>");
//对象添加后再绑定,setTimeout防止对象未创建完成
setTimeout(function(){
//阻止链接跳转(失败)
$("#hello").click (function (event) {
alert("nihao");
event.preventDefault();
});
},0);//
});
您说的正常,是指event.preventDefault();起作用,成功阻止链接跳转吗?
<script type="text/javascript">
//文档装载完毕后新加一个A
$(document).ready ( function () {
$("div#nihao").append("<a id=\"hello\" href=\"http://www.g.cn\">Google2</a>");
$("#hello").click (function () {
alert("nihao");
return false;//阻止默认事件
});
//阻止链接跳转(成功)
$("#first").click (function () {
alert("nihao");
return false;//阻止默认事件
});
});
</script>
原来代码不能执行的原因在于,$("#hello").click (function (event) {
alert("nihao");
event.preventDefault();
});执行的时候文档中还没有 #hello这个 元素,如果是要为未来要加进来的元素绑定事件的话,请用
live
$('.clickme').live('click', function() {
alert("Live handler called.");
});