簡體   English   中英

在Javascript中尋找對象

[英]finding object in Javascript

我有一個包含數千個復選框的表單,當選中一個復選框時,我想選中它下面的所有復選框。 這有效:

<html>
<body>
<form name="myform">
<input type="checkbox" name="box1" onClick="redrawboxes(this);">1<br>
<input type="checkbox" name="box2" onClick="redrawboxes(this);">2<br>
...
</form>
</body>
</html>
<script>
function redrawboxes(obj){  
    //check all boxes below 
    var foundit=false;
    for (e=0; e<document.myform.elements.length; e++){
        if (foundit==false){ //search for checked obj
            if(obj == document.myform.elements[e]){ 
                foundit=true;   
            }
        }else{ //continuing below checked box
            if(obj.checked){ //are we checking or unchecking
                    document.myform.elements[e].checked = true;
            }else{
                    document.myform.elements[e].checked = false;
            }
        }
    }
}
</script>

但是對於數千個盒子來說,IE的運行速度令人無法接受。 (Firefox運行良好。)除了遍歷整個列表之外,還有更好的方法來找到原始框嗎?

jQuery的兩個建議都很好。 對於像這樣的DOM,您最好使用一個好的庫。

關於將數千個復選框放在表單上的可疑智慧的評論也很好...

但是,如果您確實有這樣做的充分理由,並且您不能使用jQuery或類似的工具,這是一種快速,簡單的JS方法:

function redrawboxes(obj)
{  
    //check all boxes below     
    var next = obj;
    while ( (next = next.nextSibling) )
    {
      if ( next.nodeName.toLowerCase() == "input" 
        && next.type.toLowerCase() == "checkbox" )
        next.checked = obj.checked;
    }
}

在FF3,FF3.1,IE6,Chrome 1,Chromium 2中測試

我可能對此不滿意,但嘗試使用jquery。 它具有為此優化的選擇器。

里面做廣告!

如果您使用的是jQuery,則可以嘗試使用我的插件使循環異步,這將允許運行長循環而不會凍結瀏覽器。

http://mess.genezys.net/jquery/jquery.async.php

如果您不想使用jQuery,則可以下載插件並根據自己的需要修改代碼,它實際上並不依賴jQuery。

您可以像這樣讀出所選復選框的名稱:

function redrawboxes(obj) {
    var name = obj.name;
    var state = obj.checked;

    // get that index
    var index = name.substr(3) * 1; // just to be sure it's a number
    var length = document.myform.elements.length;
    var allElements = document.myform.elements

    // (un)check all elements below
    for (var i = index; i < length; i++) {
        allElements[i].checked = state;
    }
}

您可以通過使用局部變量來加快代碼的速度,並且有一個if語句可以替換。

編輯:實際上,一次性錯誤不是錯誤,因為該特定復選框由用戶本人(取消)選中。

Dunno有多快,但是您可以嘗試jQuery方式,從www.jquery.com獲取jQuery並在頁面上插入以下代碼:

$(function(){
    $("input:checkbox").click(function(){
        $(this).nextAll("input:checkbox").each(function(){
            this.checked = true;
        });
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM