JQuery - 显示/隐藏一组字段
我想使用选择的值作为条件来显示或隐藏某些字段。我不想重复自己再次编写循环只是为了显示和隐藏字段。我想使用相同的循环代码来显示或隐藏。最好的方法是什么?
hideFields = function () {
var fields = $(['#foo', '#bar', '#lorem', '#ipsum'])
showHide = function (action) {
if (action === 'show' || action === 'hide') {
action = action + '();';
fields.each(function (index, value) {
$(value).parent()
.parent()
.action(); // call show||hide here... not working...
});
}
};
if ($('#select').val() === 'something') {
showHide('hide');
}
else {
showHide('show');
}
};
hideFields();
谢谢。
I want to show or hide some fields using a select's value as criteria. I don't want to repeat myself wrinting the loop again just to show and hide fields. I want to use the same loop code to show or hide. What's the best approach?
hideFields = function () {
var fields = $(['#foo', '#bar', '#lorem', '#ipsum'])
showHide = function (action) {
if (action === 'show' || action === 'hide') {
action = action + '();';
fields.each(function (index, value) {
$(value).parent()
.parent()
.action(); // call show||hide here... not working...
});
}
};
if ($('#select').val() === 'something') {
showHide('hide');
}
else {
showHide('show');
}
};
hideFields();
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 jQuery 的toggle() 方法来显示和隐藏元素:
这样,您不必担心它们的状态,也不必让 jQuery 判断它们是否需要隐藏。
您还可以将布尔值传递给仅显示或仅隐藏元素的方法:
如果您需要执行一些额外的逻辑,您可以随时使用 $().css() 查询元素的 CSS 属性并决定要做什么从那里做。
You can use jQuery's toggle() method to show and hide elements:
That way, you don't have to worry about their state and have jQuery figure out if they need to be hidden or not.
You can also pass in a boolean to the method which will only show or only hide the elements:
And if you need to do some extra logic you can always query the elements' CSS property using $().css() and decide what to do from there.
我认为这会起作用。确保使用 option:selected 来获取选择的值。
I think this will work. Make sure you use option:selected to get the value of the select.