如何根据checkbox快速获取对应label的文本?不要根据dom关系来获取。

解决方案 »

  1.   

    什么叫“不要根据DOM关系来获取”?
    <input type="text" id="demo" labelId="test" /><label id="test" for="demo">DEMO</label>
    <script type="text/javascript">
    document.getElementById('demo').onclick = function() {
    //方法1
    var o = this.nextSibling;
    while(o.nodeType != 1) o = o.nextSibling;
    alert(o.innerHTML);

    //方法2
    var o = document.getElementsByTagName('label');
    for (var i = 0; i < o.length; i ++) {
    if (o[i].getAttribute('for') == this.id) {
    alert(o[i].innerHTML);
    break;
    }
    }

    //方法3
    alert(document.getElementById(this.getAttribute('labelId')).innerHTML);
    }
    </script>
      

  2.   

    jquery代码:$(function(){
     $("input[name=checkbox1]").bind("click",function {
       var ss = $(this).attr("id");
       var tt = $("label[for="+ss+"]").text();
       alert(tt);//显示对应的label内容
     });});
    html:
    <input id="input1" name="checkbox1" type="checkbox"/><label for="input1">111</label>
    <input id="input2" name="checkbox1" type="checkbox"/><label for="input2">222</label>
    <input id="input3" name="checkbox1" type="checkbox"/><label for="input3">333</label>
      

  3.   

    用Jquery 就不用根据dom关系获取了