且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

单击图像时选择单选按钮

更新时间:2022-01-11 22:19:22

此jquery代码可以帮助您:

This jquery code can help you:

$("a").click(function() {
    $(this).next().prop("checked", true);
});

演示: http://jsfiddle.net/k5rkxkos/

更新

在纯Javascript中(因为您说过您不是jquery的专家;)),您可以执行以下操作:

In pure Javascript (because you said that you are not expert in jquery ;) ), you can do:

var a = document.getElementsByTagName("a");
for ( var i = 0; i < a.length; i++ ) {
    a[i].onclick = function() {
        var id = this.getAttribute("data-id");
        document.getElementById(id).checked = true;
    }
}

演示: http://jsfiddle.net/k5rkxkos/1/

更新

这是根据您的更改而更新的代码:

This is the updated code according to your change:

var a = document.getElementsByTagName("a");
for ( var i = 0; i < a.length; i++ ) {
    a[i].onclick = function(e) {
        e.preventDefault();
        var id = this.getAttribute("data");
        document.querySelector('input[data="' + id +'"]').checked = true;
    }
}

注意:您必须添加输入的name属性.

Note: You must add the input name attribute.

演示