无法使用jquery选择元素段落

问题描述 投票:0回答:6
<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>

[伙计,函数func应该创建一个id为“ id”的段落,内容作为消息在id为“ stat”的标记内..它可以正常工作但是我不能使用'Jquery'选择器来使用

tag:/!我插入其中的原因是我需要解释器将“ \ n”视为新行。为什么那样,不起作用?

还有其他方法吗?

javascript jquery html paragraph pre
6个回答
1
投票

尝试一下,

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

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

您编写的代码不起作用,因为加载文档时不存在p元素。由于p元素是动态添加的,因此必须将事件附加到文档对象上


0
投票

最快的方法将是改变

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

并删除此

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

});

0
投票

这可能会帮助:

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

0
投票

改为使用.on()

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

[.on()必须能够将点击处理程序添加到动态创建的元素中,例如<p>标签为


0
投票

func中附加click事件处理程序:

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

或更妙的是:

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();
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.