<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
tag :/ ! the reason i am inserting inside in is i need the interpreter to consider "\\n" as a new line. 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. Since the p element is dynamically added, you have to attach the event to the document object
Attach the click event handler inside 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
$(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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.