1

我认为它是非常基本的面向对象的 JavaScript 相关问题。但我仍然对此感到非常困惑。我想将 $(this) 对象从 1 个函数传递给另一个函数。这样我就可以获得点击链接的href attr。

这是我的示例代码

HTML

<a href="#testblah" class="test" rel="image">TEST</a>
<a href="#blahtest" class="test" rel="video">TEST</a>

JS

$(document).on("click", ".test", function () {

var $this = $(this);
var rel = $this.attr("rel");

if (rel == "image") {
    e.preventDefault();
    openImage($this);
} else if (rel == "video") {
    openVideo($this);
}
});

function openImage($this) {

var href =  $this.attr("href");
alert(href);
}
4

2 回答 2

0

我的问题有 1 个小的语法错误(请查看问题的第一条评论)

以下是我最终使用的代码。

$(document).on("click", ".test", function (e) {

    var anchor = $(this);
    var rel = anchor.attr("rel");

    if (rel == "image") {
        e.preventDefault();
        openImage(anchor);
    } else if (rel == "video") {
        openVideo(anchor);
    }
    });

    function openImage(anchor) {
    var href =  anchor.attr("href");
    alert(href);
    }

谢谢!

于 2013-04-04T09:40:22.500 回答
0

Check out the examples in the jQuery documentation page. You'll find that the on method applies to the selected elements, in the case of your code, it's the document object. To get the attribute that you want, jQuery is not necessary to wrap the element. Here's a JSBin example. One more thing, try reemplace == with === to get type checking also. Hope it helps

于 2013-03-25T18:01:10.827 回答