gpt4 book ai didi

jquery - 我想编写更好的 jQuery 代码

转载 作者:行者123 更新时间:2023-12-03 22:52:10 26 4
gpt4 key购买 nike

我对 jQuery 比较陌生,当我尝试学习时,我担心我正在做的事情......好吧,没有错......但不一定是正确的方法。

我有下面的脚本,它运行良好并且可以完成我需要它做的事情。但看着它,我不满意,这真的是实现我目标的最佳方式还是我太挑剔了?

我正在构建的内容的简要描述:包含动态生成字段的搜索表单。每个字段都有 2 个类来指定它是否应该出现在快速和/或高级搜索表单中。用于在两个 View 之间切换的两个链接。

function searchModes() {
$('p.quicksearch-true.advancedsearch-true').show();
$('p.quicksearch-true.advancedsearch-false').show();
$('p.quicksearch-false.advancedsearch-true').hide();
$('p.quicksearch-false.advancedsearch-false').hide();
$('#advanced').show();
$('#quick').hide();

$('#advanced').click(function () {
$('p.quicksearch-true.advancedsearch-true').show();
$('p.quicksearch-true.advancedsearch-false').hide();
$('p.quicksearch-false.advancedsearch-true').show();
$('#advanced').toggle();
$('#quick').toggle();
return false;
});
$('#quick').click(function () {
$('p.quicksearch-true.advancedsearch-true').show();
$('p.quicksearch-true.advancedsearch-false').show();
$('p.quicksearch-false.advancedsearch-true').hide();
$('#advanced').toggle();
$('#quick').toggle();
return false;
});
}

HTML 如下:

<a href="#" id="quick">quick</a><a href="#" id="advanced">advanced</a>
<p class="quicksearch-true advancedsearch-true">
Some dynamically generated form field that appears in both quick and advanced search
</p>
<p class="quicksearch-true advancedsearch-false">
Some dynamically generated form field that appears in quick search only
</p>
<p class="quicksearch-false advancedsearch-true">
Some dynamically generated form field that appears in advanced search only
</p>
<p class="quicksearch-false advancedsearch-false">
Should never occur, but if it did, it would remain hidden anyway
</p>

所以说真的,我正在寻求您可能提供的任何反馈,这些反馈可以帮助我尝试编写更好的 jQuery。

非常感谢!

最佳答案

HTML:

<a href="#" id="quick" class="button" data-fields="q-field">Show Quick Form</a> <a href="#" id="advanced" class="button" data-fields="a-field">Show Advanced Form</a>

<p class="field q-field a-field">
Some dynamically generated form field that appears in both quick and advanced search
</p>
<p class="field q-field">
Some dynamically generated form field that appears in quick search only
</p>
<p class="field a-field">
Some dynamically generated form field that appears in advanced search only
</p>
<p class="field">
Should never occur, but if it did, it would remain hidden anyway
</p>

简化的 JQuery:

$(function() {
$('#advanced').show();

$('.button').click(function(e){
e.preventDefault();
$('.button').toggle('show');
$('.field').hide().parent().find('p.' + $(this).data('fields')).show();
});
});

http://jsfiddle.net/AlienWebguy/jsGmD/

关于jquery - 我想编写更好的 jQuery 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6942891/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com