javascript - 在更改语言时更改 div 的所有元素(html)?

标签 javascript jquery

我的页面上有一个下拉菜单,其中包含语言选择器选项。在选择语言时,我希望我的标签和按钮 html 根据语言进行更改吗? 我的代码

var arr = [];
    //  gets all the ids starting with comp_
    $('div[id^="comp_"]').each(function(){
        arr.push(this.id);
        labels = $(this).find('label');
        buttons = $(this).find('button');

        //get all labels inside the current div
        $(labels,buttons).each(function(){
            $(this).html("");
        });

    });
    console.log(arr);
},

*问题 * 它只更改标签元素引用而不更改按钮引用。我可以在多个元素引用上运行该函数吗?

如果我这样做会起作用,但我不想为不同的引用再次重复相同的代码

    var arr = [];
    //  gets all the ids starting with comp_
    $('div[id^="comp_"]').each(function(){
        arr.push(this.id);
        labels = $(this).find('label');
        buttons = $(this).find('button');

        //get all labels inside the current div
        $(labels).each(function(){
            $(this).html("");
        });

        $(buttons).each(function(){
            $(this).html("");
        });

    });
    console.log(arr);
},

最佳答案

是的:

    labels.add(buttons).each(function(){
        $(this).html("");
    });

或者只是:

    labels.add(buttons).html('');

少一个字符:

    labels.add(buttons).empty();

.add() jQuery 方法用于将元素添加到现有的 jQuery 集合中。这些示例使用 .add() 组合“标签”和“按钮”jQuery 对象中的元素。后两个表示如果您对每个元素做一些不变的事情,则不需要 .each()。大多数 jQuery 函数本质上都对集合的每个元素进行操作。

完全不同的简化方式:

    var labelsAndButtons = $(this).find('label, button');
    labelsAndButtons.empty();

选择器字符串中的 , 类似于“或”。该示例查找标签名称为“label”“button”的所有元素。

关于javascript - 在更改语言时更改 div 的所有元素(html)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15745435/

相关文章:

javascript - 如何在 javascript 事件中获取验证组?

jquery - 使用 .slideToggle 时如何阻止文本移动?

javascript - req.flash() 在 req.session.destroy() 之后不工作

javascript - 函数在主体卸载中调用时有效,但在作为另一个函数的一部分调用时无效

javascript - 如何简化示例中的 jQuery 代码?

php - Ajax 自动更新和服务器负载

如果高度恰好是 18px,Jquery 将向 div 添加一个类

javascript - 如何替换字符串中的反斜杠双引号?

javascript - Vue.js - 更新子组件的功能

javascript - execCommand 'undo' 在 Internet Explorer 中无法正常工作