【问题标题】:Most efficient way to add titles to elements with javascript/jQuery使用 javascript/jQuery 向元素添加标题的最有效方法
【发布时间】:2013-02-15 10:21:28
【问题描述】:

我有一些最多 24 个法语数字作为页面上段落元素中的文本(有些出现不止一次),我想浏览它们并将相关的英文翻译添加为标题属性。我有一个解决方案,但我认为它不是最有效的,所以我只是在寻找一些帮助,如果可能的话,写一些更简洁的东西,并且对你的解决方案感兴趣。

谢谢

【问题讨论】:

    标签: javascript jquery title object-literal


    【解决方案1】:

    创建一个翻译对象,其中key 是法语数字,value 是英文翻译。

    var translations = {
        "un" : "one",
        "deux" : "two",
        ...
    };
    $('.demonstration [class*="col"] p').each(function () {
        var $this = $(this);
        $this.attr('title', translations[$this.text().replace(/\s+/g, '')]);
    });
    

    【讨论】:

    • 号码不在列表中怎么办?我的回答使用|| null 来涵盖这一点。
    • @alijsh 如果该号码不在列表中,则尝试访问它将返回undefined,并且不会设置任何标题属性。
    【解决方案2】:

    改用数组和对象:

    var myTitles = { vingtquatre : 'twenty four', vingtdeux: 'twenty two' }; // add your other keys and values here in that same format, no matter what the order is inside.
    
    $(this).attr('title', myTitles[$(this).text().replace(/\s+/g, '')]);
    

    【讨论】:

      【解决方案3】:

      你可以定义一个列表:

      var nums = { 'un': 'one', 'deux': 'two', ... }
      

      然后,将switch 替换为:

      $(this).attr('title', nums[$(this).text().replace(/\s+/g, '')] || null);
      

      请注意,|| null 用于当数字不在列表中时,即它的作用类似于switchdefault 部分

      【讨论】:

        猜你喜欢
        • 2022-11-27
        • 1970-01-01
        • 2016-02-14
        • 2011-01-13
        • 2012-10-07
        • 2010-09-29
        • 2019-11-16
        • 2019-05-27
        • 2011-01-27
        相关资源
        最近更新 更多