首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >合并JQuery .focus脚本

合并JQuery .focus脚本
EN

Stack Overflow用户
提问于 2015-02-09 20:07:19
回答 2查看 21关注 0票数 0

我很好奇整合这堆Jquery .focus函数的最好方法是什么。

基本上,我使用它来允许URL具有#ID,当它这样做时,Jquery会更新页面上显示的表单。

最好的方法是合并它,这样我就不需要一遍又一遍地重复相同的代码了?

注意,所有带有ID的元素都有相同的类。

谢谢,J

--

代码语言:javascript
复制
$('#select-1').focus(function(e) {
            // set the selected choice based on URL ID
            $category_select.val('1');
            updateSupport($categorychoice.val());
        });

    $('#select-2').focus(function(e) {
            // set the selected choice based on URL ID
            $category_select.val('billing');
            updateSupport($categorychoice.val());
        });

    $('#select-3').focus(function(e) {
            // set the selected choice based on URL ID
            $category_select.val('setup');
            updateSupport($categorychoice.val());
        });

    $('#select-4').focus(function(e) {
            // set the selected choice based on URL ID
            $category_select.val('errors');
            updateSupport($categorychoice.val());
        });

    $('#select-5').focus(function(e) {
            // set the selected choice based on URL ID
            $category_select.val('customization');
            updateSupport($categorychoice.val());
        });

    $('#select-6').focus(function(e) {
            // set the selected choice based on URL ID
            $category_select.val('6');
            updateSupport($categorychoice.val());
        });
EN

回答 2

Stack Overflow用户

发布于 2015-02-09 20:14:58

为什么不给每个'select-?‘添加一个属性(比如data-source-id="item id")呢?元素之后,您可以使用css选择器附加焦点()和属性,以确定它与哪个id相关……

代码语言:javascript
复制
$(".myCssName").focus(....)

$category_select.val( $(this).data("source-id") )

建议由kpblc编辑

票数 0
EN

Stack Overflow用户

发布于 2015-02-10 20:58:14

尝试使用对象:

代码语言:javascript
复制
var values = {
  'select-1' : '1',
  'select-2' : 'billing',
  'select-3' : 'setup',
  'select-4' : 'errors',
  'select-5' : 'customization',
  'select-6' : '6'
};


$('[id^=select-]').on('focus', function(e) {
    $category_select.val(values[this.id]);
    updateSupport($categorychoice.val());
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28409408

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档