处理多个div中的特定div的事件 [英] Handle event for specific div among multiple div

查看:150
本文介绍了处理多个div中的特定div的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找有关以下情况的指南:

I'm looking for guidance on the following scenario:

上下文:页面显示动态生成的X对用户)的项目数,每个格式如下:

Context: A page displays a dynamically generated list with X (changes based on the user) number of items, each formatted as follows:

<div class="dashboard_section_item">
    <label for="add_listname_label">Assign to list</label>
    <br/>
    <select name="mod_list" class="mod_list">
        <option value="1">Option 1</option>
        <option value="2">Option 2</option>
        <option value="3">Option 3</option>
        <option value="4">Option 4</option>
    </select>
</div>



我需要在JQuery的下拉列表中处理用户选择。问题是列表在页面上重复x次,因此它只会对显示的第一个项目工作。

I need to handle the user selection in the dropdown list in JQuery. The problem is the list is repeated x times on the page, so it will only work for the first item displayed.

$(document).ready(function () {
    $(".mod_list").change(function () {
        $.ajax({
            type: 'POST',
            url: 'mod.php',
            data: 'prod_uid=' + $('.prod_uid').val() + '&mod_list=' + $(this).find(':selected').val(),
            dataType: 'json',
            success: function (response) {...
            },
            error: function () {...
            }
        });
        return false;
    });
});

我正在考虑将UID连接到列表名称标签,如:

I'm thinking about concatenating a UID to the list name tag like:

<select name="mod_list_34745727" class="mod_list">

但我不确定是否有更好的方法。

but I'm unsure whether there is a better way to do this.

如何唯一标识每个项目列表以选择其下拉值?

推荐答案

假设有很多选择 mod_list 选项,你可以使用 on()委托:

$(document).ready(function () {
    $(document).on("change", ".mod_list", function () {
        // this is the select you changed the value
        var $changedValueSelect = $(this);
        // do stuff, ajax and so on
        // print in console the selected value
        console.log($changedValueSelect.val());
    });
});

为什么委托?因为您在页面中动态添加了元素。

Why delegation? Because you have dynamically appended elements in your page.

JSFIDDLE

这篇关于处理多个div中的特定div的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆