我有这个自定义jQuery函数:
jQuery.fn.extend({
disable: function () {
return $(this).each(function () {
// function code
});
}
});
当我做这样的事情时:
container.find('input')
.disable()
.end()
.hide();
容器未隐藏,因为在结束后我没有检索容器。
如果我使用prop()
或css()
等核心功能替换禁用,则end()
会获得容器。
有没有办法让扩展函数像普通函数一样?
答案 0 :(得分:5)
请勿在{{1}}自定义功能中使用$(this)
,请使用disable()
。
this
jQuery.fn.disable = function() {
return this.each(function() {
console.log('disable');
});
};
$('#container').find('input')
.disable()
.end()
.css('background', 'yellow');
或者,您可以更改<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div id="container">
<input name="test" />
</div>
的顺序,这样您就不需要hide()
。
end()
答案 1 :(得分:0)
您已在extend方法中的上下文this
中拥有元素的jquery对象。使用$
转换是没有意义的。使用return this.each
代替return $(this).each(
jQuery.fn.extend({
disable: function () {
return this.each(function () {
console.log('disable');
});
}
});