Jquery 委托方法应用程序

Jquery delegate method application

本文关键字:应用程序 方法 Jquery      更新时间:2023-09-26

如何将 .delegate 方法应用于这一行 jquery?

$(function() {
    $("input[type='checkbox']").on('change', function() {
        if (this.checked) {
            $(".loadingItems").fadeIn(300);
            var color = encodeURI(this.value);
            $(".indexMain").load('indexMain.php?color=' + color, function() {
                $(".indexMain").fadeIn(slow);
            });
            $(".loadingItems").fadeOut(300);
        } else {
            $(".loadingItems").fadeIn(300);
            $(".indexMain").load('indexMain.php', function() {
                $(".loadingItems").fadeOut(300);
            });
        }
    });
});

形式:

echo "<input type='checkbox' class='regularCheckbox' name='color[]' value='".$colorBoxes[color_base1]."' /><font class='similarItemsText'>   ".$colorBoxes[color_base1]."</font><br />";

PHP接收颜色:

$color = $_GET['color'];
$items = $con -> prepare("SELECT * FROM item_descr WHERE color_base1 = :colorbase1");
        $items -> bindValue(":colorbase1", $color);
while($info = $items->fetch(PDO::FETCH_ASSOC)) 
{ ....

我需要允许在复选框集中进行多项选择。

现在你已经向我们展示了更多关于你真正想要做的事情,你将不得不改变你的代码的工作方式,.delegate()对解决这个问题没有用。

现在,在构造将与 indexMain.php 一起使用的 URL 时,您只检查一个复选框的值。 相反,您需要在构造该 URL 时检查所有选中复选框的值。

当选中多个复选框时,您不会说您希望如何构造 URL,但从结构上讲,代码将如下所示:

$(function() {
    $("input[type='checkbox']").on('change', function() {
        var colors = [];
        $("input[type='checkbox']:checked").each(function() {
            colors.push(this.value);
        });
        if (colors.length) {
            $(".loadingItems").fadeIn(300);
            $(".indexMain").load('indexMain.php?color=' + colors.join("+"), function() {
                $(".indexMain").fadeIn(slow);
            });
            $(".loadingItems").fadeOut(300);
        } else {
            $(".loadingItems").fadeIn(300);
            $(".indexMain").load('indexMain.php', function() {
                $(".loadingItems").fadeOut(300);
            });
        }
    });
});

当选择一种或多种颜色时,此代码将为.load()命令生成如下所示的 URL:

indexMain.php?color=blue+yellow+green+orange

如果未选择任何颜色,它将调用不带其他参数的indexMain.php

由您的服务器代码来解析 URL 中的颜色并创建所需的响应。

$(document).on('change', 'input[type=checkbox]', function() {
   // code
});

使用 jQuery .on()你可以做到这一点。

.on()的语法:

$(static_parent).on( eventName, target, handlerFunction);

其中static_parent表示target的非动态容器,target是绑定事件的元素。

委托可以写成如下

$("table").delegate("td", "click", function(){$(this).toggleClass("chosen");});

同样的事情也可以使用 latest(可从 jquery 1.7 获得)on() 实现,如下所示

$("table").on("click", "td", function(){$(this).toggleClass("chosen");});
相关文章: