使用存储在变量中的jQuery句柄

时间:2013-10-08 09:23:36

标签: javascript jquery html dom

我的脚本就像这样

(function( $ ){
   $.fn.customize_box = function() {
   //get the element id from the handle
   var my_id = this.attr('id');
   //add some layout elements before to this input box
   $('<p>hello</p>').before('#' + my_id);
      alert(my_id);
   }; 

   })( jQuery );

这是我的jquery函数编码,用于在触发元素之前和之后添加一些html元素。

$('#tags').customize_box();

这是触发代码,我为id为“tags”的输入字段触发它 我的HTML就像这里

<div class="ui-widget">
  <input id="tags" size="50"  value="sankar is playing"/>
</div>

问题是,在函数中,我获取了包含ID的触发元素属性,并且我将id保存到变量中,但我无法使用.before()编写一些html,如代码中所示,alert是提出正确,但是HELLO没有添加到内容中,有人可以协助我进行调试吗?

2 个答案:

答案 0 :(得分:3)

首先,您应该使用insertBefore,而不是before。其次,您可以使用this获取插件实例化的元素实例,因此您无需将选择器连接在一起。试试这个:

(function ($) {
    $.fn.customize_box = function () {
        var my_id = this.attr('id');

        $('<p>hello</p>').insertBefore(this);
        alert(my_id);
    };
})(jQuery);

Example fiddle

答案 1 :(得分:0)

可能有些关闭,但我认为处理函数中所有选定的元素是个好主意:

(function ($) {
    $.fn.customize_box = function () {
        return this.each(function () {
        //get the element id from the handle
        var my_id = $(this).attr('id');
        //add some layout elements before to this input box
        $('<p>' + my_id+ '</p>').insertBefore(this);
        });
    };
})(jQuery);

因此,您可以为多个输入调用它:

$('input').customize_box();

HTML:

<div class="ui-widget">
    <input id="tags" size="50" value="sankar is playing" />
    <input id="tags1" size="50" value="sankar is playing" />
    <input id="tags2" size="50" value="sankar is playing" />
</div>
相关问题