[英]Problem adding a class to a select box parent via jQuery, as is it applies to all select box parents on page
I'm having a little trouble with jQuery, I wish to have 3 separate select boxes, and when a select box is chosen the parent div then gets given that selected Option text as a class. 但是我遇到了问题,因为它显示页面上的所有值而不是单个值。
我曾尝试使用 (this) 但不幸的是我没有运气。
我的目标是例如单击中间框并将选项更改为“蓝色”,因此它的父 div 是
<div class="tableoptioncontainer Blue "</div>
但问题是这个
<div class="tableoptioncontainer ColourBlueColour"</div>
https://jsfiddle.net/jack319082/psLtarno/6/
HTML:
<div class="row-container">
<div class="tableoptioncontainer">
<select id="selectbox">
<option>Colour</option>
<option>Red</option>
<option>Orange</option>
<option>Light Orange</option>
<option>Yellow</option>
</select>
</div>
<div class="tableoptioncontainer">
<select id="selectbox">
<option>Colour</option>
<option>Light Blue</option>
<option>Blue</option>
<option>Dark Blue</option>
<option>Violet</option>
</select>
</div>
<div class="tableoptioncontainer">
<select id="selectbox">
<option>Colour</option>
<option>Dark Green</option>
<option>Moss</option>
<option>Green</option>
<option>Aqua</option>
</select>
</div>
</div>
CSS:
.row-container {
background-color: grey;
padding: 10px 20px;
display: inline-block;
}
.tableoptioncontainer {
padding: 12px;
margin: 8px 0px;
background-color: rgba(0, 0, 0, 0.2);
}
/* Background Colours for when it works */
.Red {background-color: #ff0000}
.Orange {background-color: #ff9000}
.Light-Orange {background-color: #ffc272}
.Yellow {background-color: #fff225}
.Light-Blue {background-color: #8bc2ff}
.Blue {background-color: #0078ff}
.Dark-Blue {background-color: #0030ba}
.Violet {background-color: #4603dd}
.Dark-Green {background-color: #00390f}
.Moss {background-color: #009126}
.Green {background-color: #00f13e}
.Aqua {background-color: #00f1d2}
jQuery:
jQuery(document).ready(function(){
jQuery("select").change(function(){
var colourName = jQuery('select#selectbox :selected').text();
colourName = colourName.replace(/ /g, '-');
jQuery(this).parent().attr('class','tableoptioncontainer');
jQuery(this).parent().addClass(colourName);
});
});
你必须像这样改变你的脚本
jQuery(document).ready(function(){
jQuery("select").change(function(){
var colourName = jQuery(this).find('option:selected').text();
colourName = colourName.replace(/ /g, '-');
jQuery(this).parent().attr('class','tableoptioncontainer');
jQuery(this).parent().addClass(colourName);
});
});
您的声明var colourName = jQuery('select#selectbox:selected').text();
从所有 3 个选择框中选择所选选项的文本。 请注意,id 必须是唯一的,所有选择都具有相同的id="selectbox"
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.