Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/397.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么div标记内容不隐藏?而p标记元素隐藏 为什么div内容不隐藏? $(文档).ready(函数(){ $(“p”)。单击(函数(){ $(this.hide(); }); }); TODO写入内容_Javascript_Jquery_Html - Fatal编程技术网

Javascript 为什么div标记内容不隐藏?而p标记元素隐藏 为什么div内容不隐藏? $(文档).ready(函数(){ $(“p”)。单击(函数(){ $(this.hide(); }); }); TODO写入内容

Javascript 为什么div标记内容不隐藏?而p标记元素隐藏 为什么div内容不隐藏? $(文档).ready(函数(){ $(“p”)。单击(函数(){ $(this.hide(); }); }); TODO写入内容,javascript,jquery,html,Javascript,Jquery,Html,如果你点击我,我就会消失 点击我走开 也点击我 div不会隐藏,因为您在选择器中使用了p,之后,您使用了$(this).hide()因此它会隐藏所有p元素,因为您的this关键字引用了文档中的所有p元素,所以为了选择特定的元素,您应该始终使用id,或者您可以将类与此关键字一起使用 最好将id分配给div元素,使用按钮元素,而不是隐藏特定元素,如 <html> <head> <title>Why div content does not

如果你点击我,我就会消失

点击我走开

也点击我


div
不会隐藏,因为您在选择器中使用了
p
,之后,您使用了
$(this).hide()
因此它会隐藏所有
p
元素,因为您的
this
关键字引用了文档中的所有
p
元素,所以为了选择特定的元素,您应该始终使用
id
,或者您可以将
关键字一起使用

最好将
id
分配给
div
元素,使用
按钮
元素,而不是隐藏特定元素,如

<html>
    <head>
        <title>Why div content does not hide?</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
        <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.0.min.js"></script>
        <script>
$(document).ready(function(){
  $("p").click(function(){
    $(this).hide();
  });
});
</script>

    </head>
    <body>
        <div>TODO write content</div>
        <p>If you click on me, I will disappear.</p>
<p>Click me away!</p>
<p>Click me too!</p>
    </body>
</html>


如果要切换按钮文本,则需要
If
条件来比较
按钮
元素的字符串

<div id="hide-this">
    <div>TODO write content</div>
    <p>If you click on me, I will disappear.</p>
    <p>Click me away!</p>
    <p>Click me too!</p>
</div>
<button>Hide</button>

$("button").on('click', function(){
  $("#hide-this").toggle();
}); 

为什么div内容会隐藏。你在
p标签上调用隐藏函数
你是认真的吗?您在问为什么单击
不会触发附加到
元素的事件处理程序?抱歉,跳过了这一点。我犯了一个大错误。这个问题缺乏足够的研究努力。太好了!!!!!谢谢我,h'v刚刚开始学习Javascript。@Optimight如果你开始学习Javascript,你不应该学习jQuery:)
<div id="hide-this">
    <div>TODO write content</div>
    <p>If you click on me, I will disappear.</p>
    <p>Click me away!</p>
    <p>Click me too!</p>
</div>
<button>Hide</button>

$("button").on('click', function(){
  $("#hide-this").toggle();
}); 
$("button").on('click', function(){
  $("#hide-this").toggle();
    if($(this).text() == 'Hide') { //$(this) references button element here
        $(this).text('Show');
    } else {
        $(this).text('Hide');
    }
});