简体   繁体   English

单击范围时,Javascript自隐藏父div不隐藏

[英]Javascript self hide parent div not hiding when span clicked

I have a div that's been created dynamically. 我有一个动态创建的div。 Multiple of them are created and I need to do a self parent hide, so this is what I've done: 他们创建了多个,我需要做一个自我父隐藏,所以这就是我要做的:

This Div: 这个Div:

<div><a href="">'+inputText+'-</a><div class="box"></div><span onclick="dismiss();">Close</span></div>

The Function: 功能:

function dismiss() {
    $(this).parents('div').fadeOut();
}

It's not hidding when I click the close span. 单击关闭范围时,它不是隐藏的。

Inside dismiss function this refers to window object, instead pass the this as an argument . dismiss函数内部, this引用窗口对象,而将this作为参数传递。

 function dismiss(ele) { $(ele).parents('div').fadeOut(); console.log(this); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div><a href="">'+inputText+'-</a> <div class="box"></div><span onclick="dismiss.bind(this);dismiss(this);">Close</span> </div> 

You can not access $(this) directly into any function: 您不能直接在任何函数中访问$(this)

So: pass this as parameter: 所以:将此作为参数传递:

<span onclick="dismiss(this);">Close</span>

function dismiss(obj) {
    $(obj).parents('div').fadeOut();
}

Instead of using a span for this, consider using a button. 与其为此使用跨度,不如考虑使用按钮。 It would be semantically appropriate. 这在语义上是适当的。 Maybe even change the <div> to a <p> (depending on if it is a paragraph or not). 甚至可以将<div>更改为<p>(取决于是否为段落)。 Keep in mind that you can't have a div inside ap though, so you would need to change the .box div to a span. 请记住,虽然ap中不能包含div,所以您需要将.box div更改为span。

<div>
    <a href="">'+inputText+'-</a>
    <div class="box"></div>
    <button onclick="dismiss(this);">Close</button>
</div>

And for the JS: 对于JS:

function dismiss(obj) {
$(obj).parents('div').fadeOut();
return false;
}

Another way, change the html 另一种方法,更改html

<div>
  <a href="">Click</a>
  <div class="box"></div>
  <span id="btn">Close</span>
</div>

And JS 和JS

$(document).on('click','#btn', function(){
  $(this).parents('div').hide();
});

Fiddle 小提琴

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

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