javascript Java 脚本通过 ID 更改元素的颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8206322/
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
Java script changing color of element by ID
提问by
Hi there I'm trying to do validation for a form I am working on, and I have written a function and used
嗨,我正在尝试对我正在处理的表单进行验证,并且我已经编写了一个函数并使用了
document.getElementById("span_trav_emer_med_insur").style.backgroundColor ='#FFFFFF';
I have tested my function to display an alert message box, for debugging purposes when 'trav_emer_med_insur' is checked the message box is displayed. I have checked here and on countless other sites and they all say getElementById.style.backgroundColor = 'color';
is the method to achieve what I am looking for. I don't understand at this point why it is not working, everything appears correct.
我已经测试了我的函数来显示警报消息框,因为检查了“trav_emer_med_insur”检查消息框时调试目的。我已经在这里和无数其他网站上进行了检查,他们都说这getElementById.style.backgroundColor = 'color';
是实现我正在寻找的方法。我现在不明白为什么它不起作用,一切似乎都是正确的。
Here is the starting, pertinent part of my function:
这是我的功能的开始,相关部分:
function validatePlanTypes(form) {
var error = "";
if (form.trav_emer_med_insur.checked) {
document.getElementById("span_trav_emer_med_insur").style.backgroundColor = '#FFFFFF';
if (!form.trav_emer_med_insur_opt1.checked || !form.trav_emer_med_insur_opt2.checked || !form.trav_emer_med_insur_opt3.checked || !form.trav_emer_med_insur_opt4.checked) {
form.trav_emer_med_insur_opt1.style.backgroundColor = 'Yellow';
form.trav_emer_med_insur_opt2.style.backgroundColor = 'Yellow';
form.trav_emer_med_insur_opt3.style.backgroundColor = 'Yellow';
form.trav_emer_med_insur_opt4.style.backgroundColor = 'Yellow';
error = "You must pick a plan-type for Travel Emergency Medical insurance, areas with a problem have been highlighted yellow for you.";
}
I am not testing the full function yet, I am only trying to test the very first if statement at this time, as I said the if statement works and alert("bleh"); will display an alert if I check that box
我还没有测试完整的功能,我现在只是想测试第一个 if 语句,正如我所说的 if 语句有效并且 alert("bleh"); 如果我选中该框将显示警报
Here is the HTML of the form where I am trying to change the background color of a span element surrounding the checkbox.
这是表单的 HTML,我试图在其中更改复选框周围的 span 元素的背景颜色。
<p><span name="span_trav_emer_med_insur" id="span_trav_emer_med_insur" value="span_trav_emer_med_insur" style=""><input type="checkbox" name="trav_emer_med_insur" id="trav_emer_med_insur_if" value="trav_emer_med_insur_if" class="form_elements" onClick="if(this.checked){document.getElementById('trav_emer_med_options').style.display='block';}else{document.getElementById('trav_emer_med_options').style.display='none';}"/></span> <!-- Travel Emergency Medical If Box -->
<label class="form_elements" name="label_for_trav_emer_med_insur_if" id="label_for_trav_emer_med_insur_if"> Travel Emergency Medical Insurance <em>(expands when checked)</em>.</label></p>
<p>
<div id="trav_emer_med_options" name="trav_emer_med_options" class="questions_hidden">
I have also tried
我也试过
form.span_trav_emer_med_insur.style.backgroundColor = '#FFFFFF';
Also to no avail, I'm really stumped here, the code looks identical to what I see all over the net. Someone please tell me what I am missing.
也无济于事,我真的被难住了,代码看起来和我在网上看到的完全一样。有人请告诉我我缺少什么。
Thanks, -Sean
谢谢,-肖恩
Edit - Just to verify:
编辑 - 只是为了验证:
if (form.trav_emer_med_insur.checked) {
alert("bleh");
instead of
代替
if (form.trav_emer_med_insur.checked) {
document.getElementById("span_trav_emer_med_insur").style.backgroundColor = '#FFFFFF';
Does work, so the if statement or function is not a problem.
确实有效,所以 if 语句或函数不是问题。
Complete file here - with getelementbyID not working - http://hotfile.com/dl/135598683/93484d4/general2.html
完整文件在这里 - getelementbyID 不起作用 - http://hotfile.com/dl/135598683/93484d4/general2.html
Complete file here with alert('bleh') WORKING - http://hotfile.com/dl/135598746/dc9e14b/general23.html
使用 alert('bleh') 工作完成文件 - http://hotfile.com/dl/135598746/dc9e14b/general23.html
Working PHP code showing exactly what I'm trying to do (minus the page reload part):
工作 PHP 代码显示了我正在尝试做的事情(减去页面重新加载部分):
// Check if Emergency Medical is selected.
if (isset($_POST['trav_emer_med_insur'])) {
// If Emergency Medical is selected, then check to see if an option has been selected
if (isset($_POST['trav_emer_med_insur_opt1']) or isset($_POST['trav_emer_med_insur_opt2']) or isset($_POST['trav_emer_med_insur_opt3']) or isset($_POST['trav_emer_med_insur_opt4'])) {
$SQLString = $SQLString . "emer_med, emer_med_opt1, emer_med_opt2, emer_med_opt3, emer_med_opt4";
}
// If no option is selected display error message
else {
++$ErrCount;
$Errors[$ErrCount] = "You selected interest in Travel Emergency Medical Insurance but did not select a plan-type for it";
}
}
// Check if All-Inclusive Insurance is selected.
elseif (isset($_POST['allinc_insur'])) {
//If All-Inclusive Insurance is selected, then check to see if an option has been selected
if (isset($_POST['allinc_insur_opt1']) or isset($_POST['allinc_insur_opt2'])) {
}
//If no option is selected display error message
else {
++$ErrCount;
$Errors[$ErrCount] = "You have selected interest in All-Inclusive Insurance but did not select a plan-type for it";
}
}
// Check if Cancellation Insurance is selected.
elseif (isset($_POST['cancel_insur'])) {
}
// Check if Visitor Insurance is selected.
elseif (isset($_POST['visitor_insur'])) {
//If Visitor Insurance is selected, then check to see if country is selected.
if (isset($_POST['country_select'])) {
}
// If no country selected display error message
else {
++$ErrCount;
$Errors[$ErrCount] = "You have selected interest in Visitor Insurance but have not selected a country";
}
}
//If no insurane types selected display error.
else {
++$ErrCount;
$Errors[$ErrCount] = "You haven not selected interest in any insurance plan types";
}
while ($Count != $Target) {
if (checked($QuestionNames[0]) != 1);
++$Count;
}
采纳答案by blankabout
Have you tried giving the span a colour from the start just to confirm you can see it?
您是否尝试从一开始就为跨度设置颜色以确认您可以看到它?
As your code looks prefectly ok it could be the case that you just cannot see the span background colour.
由于您的代码看起来完全正常,因此您可能无法看到跨度背景颜色。
For what it is worth I agree with the OP that using jquery for something trivial like this is a waste of bandwidth.
值得一提的是,我同意 OP 的观点,即使用 jquery 处理像这样的琐碎事情是浪费带宽。
Based on your comments I created a test page to simulate yours.
根据您的评论,我创建了一个测试页面来模拟您的。
This works:
这有效:
<span name="span_trav_emer_med_insur" id="span_trav_emer_med_insur" style='backgroundcolor:red'>
some words<input type="checkbox" name="trav_emer_med_insur" id="trav_emer_med_insur_if" value="trav_emer_med_insur_if" class="form_elements" onClick="clck(this)"/>
</span>
<label class="form_elements" name="label_for_trav_emer_med_insur_if" id="label_for_trav_emer_med_insur_if"> Travel Emergency Medical Insurance <em>(expands when checked)</em>.</label></p>
<div id="trav_emer_med_options" name="trav_emer_med_options" class="questions_hidden" style='display:none;'>
some hidden words
</div>
<script type="text/javascript">
function clck(cbObj) {
if(cbObj.checked){
document.getElementById("span_trav_emer_med_insur").style.background = "green";
document.getElementById('trav_emer_med_options').style.display='block';
}
else {
document.getElementById("span_trav_emer_med_insur").style.background = "red";
document.getElementById('trav_emer_med_options').style.display='none';
}
}
</script>
回答by Kamron
I was trying to do this exact thing. I put extra brackets in and it worked.
我正试图做这件事。我放了额外的括号,它起作用了。
As in:
如:
(document.getElementById("advert")).style.backgroundColor = "red";
回答by nicosantangelo
Your code is correct, if you want so set a background-color with javascript you access (and modify) the .style.backgroundColor property.
您的代码是正确的,如果您愿意,可以使用访问(和修改) .style.backgroundColor 属性的 javascript 设置背景颜色。
So I suppose the problem might be the html (and the styles), check this fiddle http://jsfiddle.net/hqKwd/4/I set the backgroundColor of a span that's empty, and nothing happends, but after 2 seconds I modify the innerHTML and you can see the color. The thing I'm trying to show is that being an span, it doesn't have display:block, so if you don't add that style or modify the content, you can't see anything.
所以我想问题可能出在 html(和样式)上,检查这个小提琴http://jsfiddle.net/hqKwd/4/我设置了一个空跨度的 backgroundColor,什么也没发生,但 2 秒后我修改innerHTML,您可以看到颜色。我想展示的是,作为一个跨度,它没有 display:block,所以如果你不添加那个样式或修改内容,你就看不到任何东西。
Another thing might be that the property is being override by another piece of code, but apparently this is not the case
另一件事可能是该属性被另一段代码覆盖,但显然情况并非如此
Hope it helps.
希望能帮助到你。
回答by MK_Dev
回答by jottos
I think what you are trying may not be the most productive approach.
我认为您正在尝试的可能不是最有效的方法。
You have two options here:
您在这里有两个选择:
learn how to use your browser's consoele to find out why your style settings are not working by learning how things work from the ground up or,
go with jQuery which will make your life so much better.
了解如何使用浏览器的控制台,通过从头开始了解事物的工作原理,找出样式设置不起作用的原因,或者,
使用 jQuery,它会让你的生活变得更好。
Choice 1 is worth trying, you will learn a lot about what the DOM/CSS structures look like. To do this right mouse click and choose "inspect element" when your browser of choice repsonds look for the console and literally type "document.getElementById("span_trav_emer_med_insur").style.backgroundColor" on the cmd line and see what you get. This is likely to be insightful.
选择 1 值得一试,你会学到很多关于 DOM/CSS 结构是什么样子的。为此,当您选择的浏览器查找控制台并在 cmd 行上逐字输入“document.getElementById("span_trav_emer_med_insur").style.backgroundColor”时,请右键单击并选择“检查元素”,看看您得到了什么。这很可能是有见地的。
If you want to get your job done quickly, get jQuery and try the following:
如果您想快速完成工作,请获取 jQuery 并尝试以下操作:
First to include jQuery on your page include a this line (there are other sources of jQuery as well):
首先在您的页面上包含 jQuery 包括此行(还有其他 jQuery 源):
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
in place of the code you were using:
代替您使用的代码:
document.getElementById("span_trav_emer_med_insur").style.backgroundColor ='#FFFFFF';
use the following:
使用以下内容:
$("#span_trav_emer_med_insur").css("background", "#FFFFFF");
See how these two approaches differ? What you are attempting is to understand the low level structure of the browsers DOM model and what jQuery is doing for you is providing an abstraction you can understand, which is "please change the CSS style "background" to "yellow" for me.
看看这两种方法有何不同?您正在尝试的是了解浏览器 DOM 模型的低级结构,而 jQuery 为您所做的是提供您可以理解的抽象,即“请将 CSS 样式的“背景”更改为“黄色”。
I agree with the other's who have contributed, this is really the best course of action for you. It's well worth learning jQuery.
我同意其他人的贡献,这对你来说真的是最好的行动方案。非常值得学习jQuery。
More on the jQuery CDN sites here jQuery CDNjQuery css call
有关 jQuery CDN 站点的更多信息,请点击此处jQuery CDN jQuery css 调用