I have a div that's been created dynamically. Multiple of them are created and I need to do a self parent hide, so this is what I've done:
This 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 .
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:
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). 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.
<div>
<a href="">'+inputText+'-</a>
<div class="box"></div>
<button onclick="dismiss(this);">Close</button>
</div>
And for the JS:
function dismiss(obj) {
$(obj).parents('div').fadeOut();
return false;
}
Another way, change the html
<div>
<a href="">Click</a>
<div class="box"></div>
<span id="btn">Close</span>
</div>
And JS
$(document).on('click','#btn', function(){
$(this).parents('div').hide();
});
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.