0

我正在尝试将自定义属性传递给脚本。如果我这样传递:

$('a.load-local-image').cluetip( {
local:true, 
leftOffset: $("#par-1").attr("leftpos")
);

它工作正常。但是,我需要传递当前元素的属性,而不仅仅是 par-1。如果我这样尝试:

$('a.load-local-image').cluetip( {
local:true, 
leftOffset: $(this).attr("leftpos")
);

该函数认为参数根本没有被传递。如果我这样尝试:

$('a.load-local-image').cluetip( {
local:true, 
leftOffset: function() {return $(this).attr("leftpos");}
);

它传递文字字符串 "function() {return $(this).attr("leftpos");}" 作为参数。

我知道 "$(this).attr("leftpos)" 返回正确的值,因为当我在函数调用上方立即添加这个 hack 时:

$("a.load-local-image").mouseover(function(){
    alert("leftpos=" + $(this).attr("leftpos"));
});

它显示“leftpos=220”。

这是标记:

<div id="par-1">
    <a id="load-local" class="load-local-image featurelink" title="" href="" rel="#whatever" leftpos="220" toppos="48">
    <img src="images/image.jpg" alt="" class="featureimg"></a>

我只是想将当前元素的 leftpos 值传递给函数。有人可以帮我解决这个问题。谢谢!

4

2 回答 2

0

上没有 leftpos 属性img,leftpos 属性在 上a。这可能是您问题的一部分。

于 2013-11-07T20:15:38.630 回答
0

不幸的是,this对象没有在参数中被修改。该this对象将保留this调用上下文中的对象。

$('#foo').click(function () {

    // right here the "this" object refers to $('#foo')

    $('a.load-local-image').cluetip({
        local: true, 
        leftOffset: $(this).find("img").attr("leftpos")
        //            ^- refers to $('#foo') also (same context)
    });
});

当你这样做时:

$("a.load-local-image").mouseover(function(){
    alert("leftpos=" + $(this).find("img").attr("leftpos"));
    //                   ^- refers to the $('a.load-local-image') that the event was run on
});

this对象确实包含您想要的对象,但这是因为当您在事件上运行函数时,该this对象包含触发事件的元素。

编辑:

要实现您试图通过对象实现的this目标,您可以这样做:

$('a.load-local-image').cluetip({
    local: true, 
    leftOffset: $('a.load-local-image').attr("leftpos")
});

Or:

$("a.load-local-image").mouseover(function(){
    $(this).cluetip({
        local: true, 
        leftOffset: $(this).attr("leftpos")
    });
});

编辑#2:

线索提示第一次无法打开的原因是因为您需要这样做。

// create the cluetip instance:

$("a.load-local-image").cluetip();

// now that the cluetip is created you can call it like this:

$("a.load-local-image").mouseover(function(){
    $(this).cluetip({
        local: true, 
        leftOffset: $(this).attr("leftpos")
    });
});
于 2013-11-07T20:54:02.190 回答