Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用存储在变量中的jQuery句柄_Javascript_Jquery_Html_Dom - Fatal编程技术网

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

Javascript 使用存储在变量中的jQuery句柄,javascript,jquery,html,dom,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);

我的剧本是这样写的

(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 );
这是触发代码,我为id为“tags”的输入字段触发它 我的HTML是这样的

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


问题是,在函数中,我获取了包括ID在内的已激发元素属性,并将ID保存到一个变量中,但我无法使用.before()编写一些html。正如您在代码中看到的,警报出现正确,但HELLO没有添加到内容中,是否有人可以帮助我调试它?

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

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

        $('<p>hello</p>').insertBefore(this);
        alert(my_id);
    };
})(jQuery);
(函数($){
$.fn.customize\u box=函数(){
var my_id=this.attr('id');
$(“hello

”)。在此之前插入; 警报(我的身份证); }; })(jQuery);

可能有点不对劲,但我认为处理函数中所有选定元素是个好主意:

(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);
HTML:



没问题,很乐意提供帮助。您能告诉我是否有任何函数可以在被激发的元素之后添加一些元素吗?是的,您可以使用
insertAfter()
对不起//在此输入框$('')之前添加一些布局元素。insertBefore(此)//添加终止布局元素$('its end')。insertAfter(this);警惕(我的身份证);。。这不起作用,甚至连警报都没有发出,你也能帮忙吗?你不能像那样添加元素的一部分-你必须插入整个元素。如果要环绕另一个元素,则需要使用
wrap()
$(this.wrap(“”)
(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();
<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>