Concatenate a string in JavaScript [closed]

雨燕双飞 提交于 2019-12-12 07:03:45

问题


Can anyone please help me understand how to concatenate variable prefix into my string, as shown below?

var prefix = 'q2am_utility_theme_';

$('
    #option_site_title,
    .form-text[name=\"'prefix + 'body_bg_color\"]
')

This is what I have at the moment, which isn't working. What am I doing wrong?


回答1:


Try this:

var prefix = 'q2am_utility_theme_';

$('#option_site_title, ' +
  '.form-text[name=\"' + prefix + 'body_bg_color\"]')

Note the + symbol. In JavaScript, the + operator either adds numeric values to one another or concatenates string values with one another.

The above code creates a single string of:

'#option_site_title, .form-text[name="q2am_utility_theme_body_bg_color"]'

It then uses it to make a jQuery selection, using: $(selector).

Incidentally, you don't need the \ escapes for your double-quotes because JavaScript allows strings to be formed using either single or double quotes, but one can't pair with the other.

In other words, if you write:

'.form-text[name="' + prefix + 'body_bg_color"]'

It will work just fine, because the string starts with ', and therefore treats the " character within the string as a literal, rather than an end-quote needing to be escaped. You only need the escape character if you write it as follows:

".form-text[name=\"" + prefix + "body_bg_color\"]"

Which is still valid, just harder to read, imho.




回答2:


Looks like you're missing a + sign:

var prefix = 'q2am_utility_theme_';

$(' #option_site_title, .form-text[name="'+ prefix + 'body_bg_color"]');



回答3:


As Claudio, meagar, and Kevin B stated correctly in the comments:

Jquery doesn't affect string concatenation - to concatenate a string in JavaScript, you need to unquote -> + -> variableName -> + -> quote - so it looks like:

var myName = 'foo';
alert('The name assigned is ' + myName + '.');
//shows up as: The name assigned is foo.



回答4:


Try this:

$('#option_site_title, .form-text[name="' + prefix + 'body_bg_color"]')

after putting the prefix you have:

$('#option_site_title, .form-text[name="q2am_utility_theme_body_bg_color"]')



回答5:


$("#option_site_title,.form-text[name='"+prefix+"body_bg_color']")


来源:https://stackoverflow.com/questions/16285859/concatenate-a-string-in-javascript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!