我的脚本是这样的
(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();
这是触发代码,im 为带有 id "tags" 的输入字段触发它我的 HTML 就像这里一样
<div class="ui-widget">
<input id="tags" size="50" value="sankar is playing"/>
</div>
问题是,在函数中,我获取了包括 ID 在内的触发元素属性,并将 id 保存到变量中,但我无法使用您在代码中看到的 .before() 编写一些 html,警报正确出现,但 HELLO 没有添加到内容中,有人可以帮我调试吗?
首先,你应该使用 insertBefore
,而不是 before
。其次,您可以使用this
获取插件实例化的元素的实例,因此您无需将选择器连接在一起。试试这个:
(function ($) {
$.fn.customize_box = function () {
var my_id = this.attr('id');
$('<p>hello</p>').insertBefore(this);
alert(my_id);
};
})(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);
因此,您可以为多个输入调用它:
$('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>