0

当您选择一个单选框时,我正在尝试绑定一个边框图像。这是代码:

<table width="100%">
                    <tr>
                        <td><img src="img/option/collar.png" width="100px" id="option_img"><br><input class="optionVent" type="radio" name="vent" value="1">vent</td>
                        <td></td>
                        <td><img src="img/option/collar.png" width="100px" id="option_img"><br><input class="optionVent" type="radio" name="vent" value="1">vent</td>
                    </tr></table>

这是javascript:

$(".optionVent").click(function(){
    if($(this).is(':checked')){
        $("#option_img").css('border', "solid 1px orange"); 
    }  
});

As it stands now, when 1 box is selected, both images get borders. 我想不出一种将图像绑定到单选框的方法。

谢谢,

4

3 回答 3

1
$(".optionVent").on('change', function(){
    $('img').css('border', 'none'); //add a class to be more specific
    $(this).closest('td').find('img').css('border', 'solid 1px orange'); 
});

此外,ID 是唯一的,每个 ID 只能有一个,而不是多个。

于 2013-04-23T04:03:42.380 回答
0

我会在你的样式表中添加一个类,.selected_img { border: solid 1px orange; }然后编辑你的代码和标记,如下所示:

HTML

<table width="100%">
  <tr>
    <td>
        <div class="img_box">
            <label for="vent1">
                <img src="img/option/collar.png" width="100px" id="option_img1" /><br>
                <input class="optionVent radio_img1" type="radio" name="vent" id="vent1" value="1" />
                vent one
            </label>
        </div>
    </td>
    <td></td>
    <td>
        <div class="img_box">
            <label for="vent2">
                <img src="img/option/collar.png" width="100px" id="option_img2" /><br>
                <input class="optionVent radio_img2" type="radio" name="vent" id="vent2" value="1" />
                vent two
            </label>
        </div>
    </td>
  </tr>
</table>

JS

$(".optionVent").change(function() {
    $('.img_box').removeClass('selected_img');
    $(this).closest('.img_box').addClass('selected_img');
});

CSS

.img_box {
    display: inline-block;
    padding: 20px;
}
.selected_img {
    border: 1px solid orange;
}

我喜欢添加类而不是在javascript中包含样式,以便您可以在CSS中编辑所有样式。


演示

点击查看JSFiddle 演示

于 2013-04-23T04:22:54.403 回答
0

最好的逻辑是使用 CSS 来实现边框,并简单地使用 jQuery 来添加/删除该类到选定的元素。这使 CSS 样式与 HTML 内容分开,这是它应该的样子。

$(".optionVent").click (function {
  // First, go up two levels and back down one to remove the classes
  $(this).parent().parent().children().removeclass("selected");

  // Secondly, add the class to the parent element
  $(this).parent().addclass("selected");
});

您的 CSS 将是:

.selected {
  border: solid 1px orange;
}

您可以根据需要对其进行修改以获得所需的效果。

于 2013-04-23T04:33:03.203 回答