Jquery从动态内容中获取价值

时间:2012-07-03 10:28:56

标签: javascript jquery ajax

我有一个页面,下拉菜单和下面的div。根据您从菜单中选择的内容,确定div中的负载。我需要div中动态调用的内容才能知道选择了哪个菜单值。它还需要能够检索在加载动态内容时可以更改的其他下拉菜单值。

从动态内容区域中单击提交按钮后,需要抓取所有这些值。我试图从jquery使用.parent(),但我感觉不会工作,因为我还没有能够使它工作。

非常感谢有关如何从外部动态加载的内容获取输入字段值的任何建议和帮助。

这是主页面中的Jquery和Html:

<script>
$(document).ready(function() {

    $("#men2link").click(function(){
         $.ajax({ url: 'pages/abc.php', success: function(html) {
            $("#subajax-content").empty().append(html);
            }
        });
    });
});
</script>

<table>
    <tr>
      <td>
            <table>
                <tr>
                    <td>Menu 1:</td>
                    <td>
                        <select name="men1" id="men1">
                            <option>Select Option</option>
                            <option value="o1">option1</option>
                            <option value="o2">option2</option>
                            <option value="o3">option3</option>
                        </select>
                    </td>
                </tr>
                <tr>
                    <td id="men2link">Menu 2</td>
                    <td>        
                        <select name="men2" id="men2">
                            <option>Select Option</option>
                            <option value="r">Received</option>
                            <option value="nr">Not Received</option>
                            <option value="na">Not Applicable</option>
                        </select>
                    </td>
                </tr>
            </table>
      </td>
      <td class="align-top"><div id="subajax-content"></div></td>
    </tr>
</table>

Html&amp;动态加载到subajax-content div的JQuery

<script>
$(document).ready(function() {
    $("#save").click(function(){
       alert($("#home").parent("#men2").val());
    });
});
</script>

2 个答案:

答案 0 :(得分:0)

您可以使用“nearest()”而不是parent(),因为它不是那么严格

答案 1 :(得分:0)

首先,使外表可识别。对于唯一的表,您可以使用id或重复表,使用类:

<table id="outerTable">
<!-- or -->
<table class="outerTable">

现在你只需要一个jQuery块。这将响应动态插入的内容,因此不需要再提供内容的javascript / jQuery。

$(document).ready(function() {

    //This part is unchanged
    $("#men2link").click(function() {
        $.ajax({
            url: 'pages/abc.php', 
            success: function(html) {
                $("#subajax-content").empty().append(html);
            }
        });
    });

    //This part is a modified version of what was previously delivered with the dynamic content
    //For use with id="outerTable"
    $("#outerTable").on('click', "#save", function() {
        var $outerTable = $(this).closest(".outerTable"),
            val1 = $outerTable.find("#men1").val(),
            val2 = $outerTable.find("#men2").val();
        alert([val1, val2]);
    });
});

注意:

  • 对于重复使用内部表的外部表,代码会略有不同。
  • 对于在唯一外部表中重复内部表,代码会略有不同。
  • 重复外部表格或重复内部表格时,选择菜单和保存按钮也应该有类而不是ID。