jQuery:选择文本节点的上一个兄弟节点

时间:2012-12-28 20:54:23

标签: javascript jquery textnode siblings

假设我们有以下HTML代码:

<div>
    Select Gender:
    <input type="radio" />
    Male
    <input type="radio" />
    Female
</div>

我的目标是检查男性单选按钮(第一个)。但是,我不知道这个单选按钮是否总是两个单选按钮中的第一个,唯一可以肯定的是我想检查之前的单选按钮“男性”文本。

所以我就这样做了:

$('div') 
    .contents()
    .filter(function() {
        return (((this.textContent || this.innerText || $(this).text() || '').search(new RegExp(labels[i], "ig")) >= 0) && (this.nodeType === 3)); 
    })   
    .prev('input[type=radio]')
    .attr('checked', 'checked');

但这不起作用。快速调试显示正确选择了文本节点,但是.prev()函数没有返回任何内容。我也曾尝试使用previousSibling但没有更好的结果。

提前致谢!

2 个答案:

答案 0 :(得分:2)

$('div').contents().filter(function() {
     var tn = this.textContent || this.innerText;
     return $.trim(tn) === 'Male';
}).prev('input[type=radio]').prop('checked', true);

http://jsfiddle.net/FdHAa/

或者:

<div>
    Select Gender:
    <input id='male' type="radio" />
    <label for='male'>Male</label>
    <input id='female' type="radio" />
    <label for='female'>Female</label>
</div>

$('div label').filter(function() {
    return $(this).text() === 'Male';
}).prev().prop('checked', true);

答案 1 :(得分:0)

检查“男性”文字前的单选按钮。

http://jsfiddle.net/hmariod/ZtuKD/1/

function setM() {
    var inps = document.getElementsByTagName("input");
    for(var i = 0; i < inps.length; i++){
        if(inps[i].type == "radio" ){
            if(inps[i].nextSibling.data.indexOf("Male") > -1){
                inps[i].setAttribute("checked","checked");
            }
        }
    }
}