简体   繁体   English

jQuery中的连接

[英]Concatenation in jQuery

var os = $.client.os; // mac
var browser = $.client.browser; // firefox
var browserversion = $.client.browserversion; // 3
$('#root').addClass( os + browser + browserversion );

.. results in <div id="root" class="macfirefox3"> . ..结果<div id="root" class="macfirefox3"> How do I add spaces between them? 如何在它们之间添加空格?

$('#root').addClass( os + " " + browser + " " + browserversion );

Another variation of the same: 另一个变种:

$('#root').addClass([
    $.client.os,
    $.client.browser,
    $.client.browserversion
].join(' '));

Considering jQuery's philosophy, the addClass method should really accept an array or multiple strings as arguments without you having to concatenate them. 考虑到jQuery的理念,addClass方法应该真正接受一个数组或多个字符串作为参数,而不必连接它们。

So here's my 2 cent plugin called addClasses, basically a wrapper around what Marko did. 所以这是我的2分插件名为addClasses,基本上是Marko所做的包装。

jQuery.fn.addClasses = function() {
    var classes = [];
    $.each(arguments, function(index, name) {
        classes.push(name);
    });
    this.addClass(classes.join(' '));
};

Allows you to send any number of class names as string arguments. 允许您将任意数量的类名称作为字符串参数发送。

$('div').addClasses('message', 'greeting', 'w00t');

你需要连接空间,Falcon已经给你一个例子了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM