Greater area for radio selection

2019-02-19 03:12发布

<span>
   <img src="img/icon.png" alt="" />
   <label><input type="radio" name="" /> Label here</label>
</span>

I want the whole <span> to be clickable, not just the radio input. How do I do it with jQuery?

5条回答
趁早两清
2楼-- · 2019-02-19 03:21

This is a better way.

$('span').click(function() {
    $(this).find('input').attr({checked:"checked"});
});

Just keep in mind that you are adding a click event to all spans. Better would be to have a class on the span and reference that.

$('.myClickySpan')...

<span class='myClickySpan'>...
查看更多
Juvenile、少年°
3楼-- · 2019-02-19 03:31

It looks like you're not using the for attribute of the label. Maybe doing so will help you

<input type="radio" name="r" id="r" />
<label for="r">
   <img src="img/icon.png" alt="" />
   Label here
</label>
查看更多
放荡不羁爱自由
4楼-- · 2019-02-19 03:38

You could do it without jQuery by just making the <span> the <label> instead:

<label for="some-id">
   <img src="img/icon.png" alt="" />
   <input type="radio" name="" id="some-id" /> Label here
</label>
查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-02-19 03:38
$("span").click(function(){
  var radio = $(this).find('input:radio');
  //do whatever with the radio button
});

I believe should do it.

查看更多
beautiful°
6楼-- · 2019-02-19 03:45

Well, the easiest solution would be to wrap everything inside the <label> tag, like this:

<label for="foo">
    <img src="img/icon.png" alt="" />
    <input type="radio" name="" id="foo" />
</label>

When you specify an for attribute to label, and the same id to the field, the label becomes clickable and will activate the corresponding input.

But, if you for some reason need to do it in jQuery, this should work:

$('span').click(function() {
    $(this).find('input').click();
    return false;
});
查看更多
登录 后发表回答