jQuery end() 不适用于 extend()
jQuery end() not working with extend()
我有这个自定义 jQuery 函数:
jQuery.fn.extend({
disable: function () {
return $(this).each(function () {
// function code
});
}
});
当我做这样的事情时:
container.find('input')
.disable()
.end()
.hide();
容器未隐藏,因为结束后我没有检索到容器。
如果我用 prop()
或 css()
之类的核心函数替换禁用,则 end()
获取容器。
有没有办法让扩展函数的行为像普通函数一样?
不要在 disable()
自定义函数中使用 $(this)
,请使用 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()
。
container
.hide()
.find('input')
.disable();
您已经在扩展方法的上下文 this
中有 jquery 个元素对象。使用 $
转换是没有意义的。使用 return this.each
而不是 return $(this).each(
jQuery.fn.extend({
disable: function () {
return this.each(function () {
console.log('disable');
});
}
});
我有这个自定义 jQuery 函数:
jQuery.fn.extend({
disable: function () {
return $(this).each(function () {
// function code
});
}
});
当我做这样的事情时:
container.find('input')
.disable()
.end()
.hide();
容器未隐藏,因为结束后我没有检索到容器。
如果我用 prop()
或 css()
之类的核心函数替换禁用,则 end()
获取容器。
有没有办法让扩展函数的行为像普通函数一样?
不要在 disable()
自定义函数中使用 $(this)
,请使用 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()
。
container
.hide()
.find('input')
.disable();
您已经在扩展方法的上下文 this
中有 jquery 个元素对象。使用 $
转换是没有意义的。使用 return this.each
而不是 return $(this).each(
jQuery.fn.extend({
disable: function () {
return this.each(function () {
console.log('disable');
});
}
});