I'm trying to use closest with attr, but I can't get id.
function checkID() { id = $(this).closest('div').attr('id'); alert(id); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="preview-image" id="prv-img"> <div class="preview-remove" data-name="${fileName}" onclick="checkID()" id="prv-rmv">×</div> <img src="/images/examplefile.png" alt=""> <div class="preview-info" id="prv-inf">${fileName}</div> </div>
The reason why it's not working is that in your checkID()
function, jQuery
don't know what this
refer to, so use:
function checkID(obj) {
var id = $(obj).closest('div').attr('id');
alert(id);
}
and
onclick="checkID(this)"
Demo
function checkID(obj) { var id = $(obj).closest('div').attr('id'); alert(id); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="preview-image" id="prv-img"> <div class="preview-remove" data-name="${fileName}" onclick="checkID(this)" id="prv-rmv">×</div> <img src="/images/examplefile.png" alt=""> <div class="preview-info" id="prv-inf">${fileName}</div> </div>
How you can use this
in function? You must specify "this" in the onclick
call then use it in the function
function checkID(el) { id = $(el).closest('div').attr('id'); alert(id); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="preview-image" id="prv-img"> <div class="preview-remove" data-name="${fileName}" onclick="checkID(this)" id="prv-rmv">×</div> <img src="/images/examplefile.png" alt=""> <div class="preview-info" id="prv-inf">${fileName}</div> </div>
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.