我可以将$(this)用作javascript变量吗? [英] Can I use $(this) as a javascript variable?

查看:107
本文介绍了我可以将$(this)用作javascript变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

这是代码.

HTML

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

JavaScript:

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

推荐答案

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

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

这篇关于我可以将$(this)用作javascript变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆