如何组合多个 $(document).ready() 函数


How to compose multiple $(document).ready() function

我有一个创建动态<select>的函数。我必须使其成为多选选项,所以我也必须初始化它。

该函数被多次调用;下面是函数:

function renderTimezoneFilterStringCriteria($filterKey,$onChange,$r,$c,$for)
    {
        echo '<script>
                $(document).ready(function()
                {
                    $("#zoneFilter_criteria_'.$for.'_'.$r.'_'.$c.'").multiselect({
                    includeSelectAllOption: true,
                    enableFiltering: true,
                    enableCaseInsensitiveFiltering: true,
                    maxHeight: 150
                 });
                });
                </script>'.'<div class="time_zone_list"><select name="rules['.$r.']['.$c.']['.$for.'_timezone]" class="input_field zonefield" id="zoneFilter_criteria_'.$for.'_'.$r.'_'.$c.'"  style="width:30%; margin-right:5px; float:left;">';
        foreach ($this->timezoneArrayNotDefault as $k => $val) {
            $selected = '';
             $val_array = explode(")",$val);
            if (isset($val_array[1]) && trim($val_array[1]) == trim($filterKey)) {
               echo $selected = SELECTED;
            }
            echo '<option value="' . $val . '"' . $selected . '>' . $val . '</option>';
        }
        echo '</select></div>';
    }

现在,正如你所看到的,html是作为php字符串制作的(我的客户说,通过这种方式,html加载得更快,所以他使用了这种技术,你不能说服他改变另一种方式。

现在让我们进入正题:如果函数被多次调用,那么它也会导致多个 $(document).ready(function(){});

有什么办法,我只能$(document).ready(){});并以其他方式初始化多个下拉列表?

设置一个标志变量。

$firstCall = TRUE;
renderTimezoneFilterStringCriteria($filterKey,$onChange,$r,$c,$for, &$firstCall);

并检查它:

function renderTimezoneFilterStringCriteria($filterKey,$onChange,$r,$c,$for, &$firstCall)
    {
        if($firstCall) {
            echo '<script> $(doucment).ready(function() { ... '; 
            //your document.ready here
            $firstCall = FALSE;
        }
    // your other stuff here
    }

UPD:更好的解决方案可能是使单个函数回显您的文档.ready,并调用它一次。

下面是在添加新 html 时重新绑定代码的示例。

http://jsfiddle.net/64e41LL9/

目录

<div id="container">
   <button class="button-item">I am a button</button>
</div>
<br/>
<button id="add-html" >add button</button>
<br/>
<button id="rebind" >rebind</button>

Jquery

$(document).ready(function(){
    //function to rebind
    function rebind() {
        $('.button-item').click(function(){
           alert("Im binded");
        })             
    }
    //initial bind on page load
    rebind()
    //adding new html thats unbinded
    $("#add-html").click(function(){
         $("#container").append('<button class="button-item">I am a button</button>')
    })
    //calls function to bind new html 
    $("#rebind").click(function(){
        rebind()
    })
})

这里发生的事情至关重要的是,当页面加载时,您最初会将警报代码绑定到按钮,但是当您将新的html附加到页面时,您将看到新按钮不会触发单击事件,即使它具有相同的类。这是因为它没有绑定。单击该重新绑定按钮后,它将使用该类(按钮项)重新绑定所有按钮。您可以使用相同的概念,但每次添加动态 html 时,它都会调用重新绑定函数。