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