2010-09-17 81 views
2

我正在研究一个JQuery插件,并且在创建DOM元素和附加一个单击事件时遇到问题。我创建的DOM元素代码如下所示:当页面和但是每个元素click事件触发上呈现jQuery:插入DOM元素并附加事件

return this.each(function() { 
     $this = $(this); 

     $("<div class=\"" + settings.headingClass + "\">" + $this.attr("title") + "</div>").insertBefore($this).click(function() { 
      alert($this.attr("title")); 
     }); 
    }); 

$this.attr("title")值是正确的,警告框始终显示的$this.attr("title")的价值最后的元素。

实施例:

我的插件正被施加到与标题“标题1”,“标题2”和“TITLE3” 3个元素。生成的HTML将正确显示这些标题,但无论点击哪个标题元素,警报框都只显示“标题3”。

任何想法?

额外信息

我提供一些额外的信息,以帮助这一点。我正在创建一个基本的扩展器插件来尝试使用JQuery插件开发。 HTML元素的

实施例:

<div class="MyExpander" title="Title1"> 
    This is my expanders content 
</div> 

JS创建JQuery的膨胀:

$(".QuizExpander").expander({ 
    "headingClass": "ExpanderHeading" 
}); 

插件迄今代码:

(function ($) { 
$.fn.expander = function (options) { 
    var settings = { 
     "headingClass": "", 
    }; 

    if (options) { 
     $.extend(settings, options); 
    } 

    return this.each(function() { 
     $this = $(this); 

     $("<div class=\"" + settings.headingClass + "\">" + $this.attr("title") + "</div>").insertBefore($this).click(function() { 
      alert($this.attr("title")); 
     }); 
    }); 
}; 

})(jQuery的);

回答

2

编辑:你这种行为的原因是忘记使用var具有函数的局部变量。未能使用var而是创建全局变量。

因此,click()函数中的$this函数是全局函数,而不是您在each()中定义的函数。


原来的答复:有一些明显的问题与您的代码,但原则上它应该工作(至少它为我,见http://jsfiddle.net/CpeNM/)。

您的代码示例缺少相关部分,或者我误解了该问题。无论如何 - 这是我认为你的代码一般是错的:

return this.each(function() { 
    // ALWAYS!!! use the var keyword for local variables (or global ones will be created) 
    var $this = $(this); 
    // use the jQuery functions to modify new DOM objects, avoid string-building 
    var $div = $("<div>").addClass(settings.headingClass).attr("title", $this.attr("title")); 

    $div.insertBefore($this).click(function() { 
    // theoretically you could use 'alert($(this).text());' here 
    alert($this.attr("title")); 
    }); 
});​ 
+0

$ this变量缺失导致问题。所以这是全局变量的问题。说得通! – Jason 2010-09-17 17:30:42

+0

@Jason:关于“避免字符串构建”部分:除非你处于非常高需求的循环中,这会显着地阻止用户界面,否则你应该更喜欢使用DOM方法(和他们的jQuery包装器)来构建DOM对象。连接来自字符串的复杂HTML只是太简单了。在jQuery中,它比替代选项更加丑陋。 – Tomalak 2010-09-17 17:41:28

0

this.each()的每个低谷中,$this被覆盖。所以,你不得不说这样的事情(如果以下this是一个jQuery对象,否则你就必须换一个$()周围):

return this.before(
    $('<div class="' + settings.headingClass + '">' + this.attr("title") + '</div>') 
    .click(function() { 
    alert(this.attr("title")); 
    }); 
}); 
+0

@elektronik:这将工作,但并不能解释为什么OP首先看到的问题。 ;-) – Tomalak 2010-09-17 17:43:18

0
return this.each(function() { 
    $this = $(this); 
    $("div", $(this)).live('click', function() { 
     alert($this.attr("title")); 
    }); 

    $("<div class=\"" + settings.headingClass + "\">" + $this.attr("title") + "</div>").insertBefore($this); 
}); 

基本上,我是分裂成两个电话。 live()不需要DOM元素存在以供事件应用。

http://api.jquery.com/live/

+0

这不是问题,因为$ this在this.each()的每次演练中都会被覆盖。 (请参阅我的回答) – elektronikLexikon 2010-09-17 16:56:21