繁体   English   中英

我可以将$(this)用作javascript变量吗?

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

我正在编写一个函数,该函数需要知道单击的div的位置。

我想知道是否可以将单击对象的位置作为javascript变量获取?

这是代码。

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是指当前元素。

在jQuery中,由于他们使用$()获取元素,因此$(this)返回的是jQuery相当于普通JS的this

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

$()返回一个DOM元素 (就像一个可以使用其方法属性等的对象),如果您为其设置了变量,则该变量必须像jQuery-Object一样正常工作。 但是以我的经验,有时候不行 我知道最好的方法是通过jQuery-selector( $ )获取变量。 您的代码是正确的,但是如果应用以下更改,则代码会更好:

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"});
}

暂无
暂无

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

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