简体   繁体   中英

Can I use $(this) as a javascript variable?

I'm writing a function which requires knowing the location of the clicked div.

I'm wondering if I can get the location of a clicked object as a javascript variable?

here is the code.

HTML

<area shape="rect" coords="103, 0, 213, 25" href="#" onClick="swap3($(this),'product-details','product-specs');">

Javascript:

function swap3(currentDivId ,oldDivId, newDivId) {
    var oldDiv = currentDivId.nextAll("div." + oldDivId);
    var newDiv = currentDivId.nextAll("div." + newDivId);
    oldDiv.style.display = "none";
    newDiv.style.display = "block";
}

this refers to the current element.

In jQuery, as they use $() to get an element, $(this) returns the jQuery equivalent of vanilla JS's this .

<area shape="rect" coords="103, 0, 213, 25" href="#" onClick="swap3(this,'product-details','product-specs');">

$() returns a DOM element (like an object that you can work with it's methods , properties , etc) and if you set a variable to it, the variable must work like an jQuery-Object correctly. But in my experience, some times that DO NOT ! and I learn the best way is to get the variable by jQuery-selector ( $ ). Your code is correct, but should be better if you apply these changes:

function swap3(currentDivId ,oldDivId, newDivId) {
    var oldDiv = $(currentDivId).nextAll("div." + oldDivId);
    var newDiv = $(currentDivId).nextAll("div." + newDivId);
    $(oldDiv).css({"display" : "none"});
    $(newDiv).css({"display" : "block"});
}

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.

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