jQuery给出输入ID,获取标签文本

del*_*win 15 html forms checkbox jquery

在我的HTML表单中(与大多数HTML表单一样),标签与字段共享相同的ID.一旦单击具有匹配ID的复选框,我就会尝试返回标签标签的HTML.

<input id="yes1" type="checkbox">
<label for="yes1">This is the text it should return.</label>
Run Code Online (Sandbox Code Playgroud)

而我的jQuery:

$('input').change(function() {
    if (this.checked) {
        var response = $('label#' + $(this).attr('id')).html();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,唉,响应是NULL.

Ali*_*guy 35

$('input').change(function() {
    if (this.checked) {
        var response = $('label[for="' + this.id + '"]').html();
    }
});
Run Code Online (Sandbox Code Playgroud)

无需从属性中获取id.

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