我想改变父元素的输入元素样式,当它被选中时
<div> <!--- this is the parent element --->
<input type="radio" data-dynamic-update="1" name="virtuemart_paymentmethod_id" id="payment_id_3" value="3" checked="checked">
</div>
我在谷歌搜索后发现了这个:
var x = document.getElementById("payment_id_3");
x.addEventListener("click", function(){
$(x).parent().css({"background-color": "green", "border": "1px solid green"});
});
但它不起作用..我怎么能这样做?
答案 0 :(得分:1)
这就是你如何做到的。此示例代码显示如何使用多个单选按钮并更改父div
的样式。
<html>
<head></head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<style>
#parent{
width: 100px;
height: 200px;
background-color: orange;
}
</style>
<body>
<div id="parent">
<input type="radio" id="green" name="color"> Green<br>
<input type="radio" id="pink" name="color"> Pink<br>
<input type="radio" id="purple" name="color"> Purple<br>
<input type="radio" id="red" name="color"> Red
</div>
<script type="text/javascript">
$("#parent input[type=radio]").on('click',function(){
var theId = $(this).attr('id');
if (theId =="green")
{
$("#parent").css({"background-color":"green"});
}
else if (theId == "pink")
{
$("#parent").css({"background-color":"pink"});
}
else if (theId == "purple")
{
$("#parent").css({"background-color":"purple"});
}
else
{
$("#parent").css({"background-color":"red"});
}
})
</script>
</body>
</html>
&#13;
注意:上面是一个让您了解如何操作的例子。根据需要更改样式。
在你的情况下,它可以用这些简单的线条。
$("#payment_id_3").click(function(){
$(this).parent().css({"background-color":"green","border": "1px solid green"});
});
注意:在你的情况下,你应该在初始阶段为你的父div定义一些样式,例如width,heigh。假设你已经完成了。
答案 1 :(得分:1)
使用“更改”事件和“准备好文档”事件更新解决方案:jsfiddle
$(document).ready(function() {
$('#payment_id_3').on('change',function(){
if (this.checked) { //Checked CSS
$('#payment_id_3').parent().css({
'background-color': 'green',
'border': '1px solid green'
});
} else { // unchecked CSS
$('#payment_id_3').parent().css({
'background-color': 'red',
'border': '1px solid black'
});
}
});
$('#payment_id_3').trigger('change');
});
注意:我已将“收音机”更改为复选框。 编辑:更新了JSFiddle链接和代码
答案 2 :(得分:0)
获取小提琴:https://jsfiddle.net/45tb5rn5/
问题在于获取元素对象:
$('#payment_id_3').click(function(){
$('#payment_id_3').parent().css({"background-color": "green", "border": "1px solid green"});
});
答案 3 :(得分:0)
你应该只为所有人使用jQuery,如下所示:
var x = $("#payment_id_3");
x.click(function(){
$(this).parent().css({"background-color": "green", "border": "1px solid green"});
});
答案 4 :(得分:0)
如果你正在使用jQuery,那么试试这个:
$('#payment_id_3').on("change", function(){
$(this).parent().css({"background-color": "green", "border": "1px solid green"});
});
答案 5 :(得分:0)
以下是选中复选框后可以更改div的方法示例。
$('#payment_id_3').click(function(){
if($(this).prop('checked')){ // if checked
$(this).parents('div').css('background-color','red');
}
else{ // if not checked
$(this).parents('div').css('background-color','teal');
}
})
您可以在这里查看Example的实际操作。