简体   繁体   English

无法使用 jquery 选择元素段落

[英]Unable to select element paragraph using jquery

<html>
<head>
<script>
$(document).ready(function(){
 $("p").click(function(){
     $(this).hide();
  });

});
  function func(){
var s = "<p id=" + id +">"+"<center>"+"<h2><b>Topic :</b></h2>"+message+"</center></p><br>";
document.getElementById("stat").innerHTML+=s;

}
</script>



</head>
<body>
//call function func
<pre id="stat" > </pre>
</body>
</html>

Guys the function func is supposed to create a paragraph with id as "id " and the content as a message inside the tag with id as "stat " .. it works fine But i cant use the 'Jquery' selector to use the click function on伙计们,函数 func 应该创建一个段落,id 为“id”,内容为标签内的消息,id 为“stat”..它工作正常但我不能使用“Jquery”选择器来使用点击功能在

tag :/ !标签:/! the reason i am inserting inside in is i need the interpreter to consider "\\n" as a new line.我在里面插入的原因是我需要解释器将“\\n”视为新行。 Why is that , not working ?为什么那不行?

and is there any other way to do it ?还有其他方法可以做到吗?

Try this,试试这个,

$(document).ready(function(){
 $(document).on('click','p',function(){
     $(this).hide();
  });    
});
$(document).on('click', 'p', function() { $(this).hide();})

The code you wrote is not working because the p element is not present when the document is loaded.您编写的代码不起作用,因为加载文档时 p 元素不存在。 Since the p element is dynamically added, you have to attach the event to the document object由于 p 元素是动态添加的,所以必须将事件附加到文档对象上

Attach the click event handler inside func :func附加点击事件处理程序:

function func(){
    var s = "<p id=" + id +">"+"<center>"+"<h2><b>Topic :</b></h2>"+message+"</center></p><br>";
    document.getElementById("stat").innerHTML+=s;


    $("#" + id).click(function(){
        $(this).hide();
    });
}

Or better still:或者更好:

function func(){
    var s = $("<p id=" + id +">"+"<center>"+"<h2><b>Topic :</b></h2>"+message+"</center></p><br>");
    $("#stat").append(s);

    s.click(function(){
        $(this).hide();
    });
}

the fastest way will be to change最快的方法是改变

var s = "<p id=" + id +">"+"<center>"+"<h2><b>Topic :</b></h2>"+message+"</center></p><br>";

to

var s = "<p id=" + id +" onclick=\"$(this).hide()\">"+"<center>"+"<h2><b>Topic :</b></h2>"+message+"</center></p><br>";

and delete this并删除这个

$(document).ready(function(){
 $("p").click(function(){
     $(this).hide();
  });

});

This may help:这可能有帮助:

$('body').on('click', 'p', function(){
   $(this).hide();
});

use .on() instead使用.on()代替

 $(document).on('click', 'p', function(){
     $(this).hide();
  });

.on() has to ability to add a click handler to elements that are created dynamically , like your <p> tags are .on()必须能够向动态创建的元素添加点击处理程序,例如您的<p>标签

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM