javascript jQuery:为 ID + 变量设置 css 背景颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8066851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 02:08:47  来源:igfitidea点击:

jQuery: Set css background-color for an ID + Variable

javascriptjquerycssvariables

提问by jQuerybeast

I am trying to set a background color for an ID + Variable but I can't figure it out. There must be something really small that I am not aware of.

我正在尝试为 ID + 变量设置背景颜色,但我无法弄清楚。一定有一些我不知道的非常小的事情。

Here is what I have:

这是我所拥有的:

var abc = $dialog.data( "url" );
alert(abc)

This Alerts: item1

此警报:item1

var cde = '#' + abc
alert(cde)

This Alerts: #item1

此警报:#it​​em1

So far so good. Now, I'm trying to change the background for that ID. So:

到现在为止还挺好。现在,我正在尝试更改该 ID 的背景。所以:

This works:

这有效:

$(body).css('background-color', 'black');

This doesn't:

不会

cde.css('background-color', 'black');
$(cde).css('background-color', 'black');
$("#" + abc).css('background-color', 'black');

All are in the same function.

都在同一个函数中。

What I'm I doing wrong?

我做错了什么?

Thanks a lot

非常感谢

回答by MCSI

If you try this, does it work?

如果你试试这个,它有效吗?

$('#item1').css('background-color', 'black');

回答by Dominic Goulet

The only reason I see that your code is not working is because the value that you pass to jQuery (namely cde or "#" + abc) is not of type "String".

我看到您的代码不起作用的唯一原因是您传递给 jQuery 的值(即 cde 或“#”+abc)不是“String”类型。

You can do some test for that :

你可以做一些测试:

var test = "#item1";
alert(test === cde);
alert(typeof(cde));

If the type is not string, then you could simply do :

如果类型不是字符串,那么您可以简单地执行以下操作:

$(cde.toString()).css('background-color', 'black');

回答by Marthin

EDITED: How about forcing it to a string like this?

编辑:如何将其强制为这样的字符串?

$("" + cde).css('background-color', 'black');

回答by Alnitak

Instead of using alert(), use console.log().

而不是使用alert(),使用console.log()

alert()has a habit of automatically calling .toString()on objects, and also flattening arrays.

alert()有自动调用.toString()对象的习惯,也有扁平化数组的习惯。

I expect what's happening is that your variable abcis not actually a string, so what you probably have is the result of:

我希望发生的事情是您的变量abc实际上不是字符串,因此您可能拥有的是以下结果:

'#' + abc.toString()

回答by Vitim.us

document.getElementById('item1').style.backgroundColor='black';

this always works!

这总是有效的!