1

我有一个需要使用动态添加的对象的过程。如何在 Jquery 中访问这些对象。

当前:当 transtypes 值等于“转入”或“转出”时,不显示两个 div 标签“#transferorProfileGroups”和“#transfereeProfile”。

我想要的结果:在满足条件时显示或隐藏这些 div 标签。

var JSON = JSON || {};
// implement JSON.stringify serialization
JSON.stringify = JSON.stringify || function (obj) {
var t = typeof (obj);
if (t != "object" || obj === null) {
    // simple data type
    if (t == "string")
        obj = '"' + obj + '"';
    return String(obj);
} else {
    // recurse array or object
    var n, v, json = [], arr = (obj && obj.constructor == Array);
    for (n in obj) {
        v = obj[n];
        t = typeof (v);
        if (t == "string")
            v = '"' + v + '"';
        else if (t == "object" && v !== null)
            v = JSON.stringify(v);
        json.push((arr ? "" : '"' + n + '":') + String(v));R
    }
    return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
}
};

$(document).ready(function () {
setJobExceptionDataTable();

handleTransferTypeSelection();

});

function handleTransferTypeSelection() {
$('#tranTypes').live('change' , function () {
alert("help")
    var transfertypesvalue = $(this).val();

    if (transfertypesvalue == "Transfer In") {
        $('#transferorProfileGroups]').removeClass('invisible');
        $('#transfereeProfile').addClass('invisible'); 

    }
    else if (transfertypesvalue == "Transfer Out") {
        $('#transfereeProfile').removeClass('invisible');
        $('#transferorProfileGroups').addClass('invisible');
    }
    else {
        $('#transfereeProfile').addClass('invisible');
        $('#transferorProfileGroups').addClass('invisible');
    }
});
}

function getJobExceptionDetails(jobId, jobName, jobStatus, jobSubmitted, jobExceptionType) {
var getDetailsUrl = '';
var setTables = '';

switch (jobExceptionType) {
    case "ProfileSelectionRequired":
        setTables = setProfileSelectionRequiredDataTables;
        getDetailsUrl = "/JobException/GetProfileSelectionRequiredDetails";
        break;
    default:
        alert('JobExceptionType not defined. (' + jobExceptionType + ')');
        return false;
        break;
}

$.ajax({
    url: getDetailsUrl,
    type: "GET",
    data: {
        JobId: jobId,
        JobStatus: jobStatus,
        JobSubmitted: jobSubmitted,
        JobName: jobName,
        JobExceptionType: jobExceptionType
    },
    beforeSend: function () {
        $('#loading').show();
    },
    success: function (result) {
        $(".detailsModalContent").append(result);

        setTables();

        $("#detailsModal").modal({
            autoResize: true,
            autoPostition: true,
            closeHTML: "",
            dataCss: {
                padding: "10px"
            },
            minHeight: 350,
            maxHeight: 700,
            minWidth: 900,
            maxWidth: 900,
            overlayClose: true
        });

        $("#btnResolveProfileSelectionRequired").click(function () {
            handleResolveProfileSelectionRequired();
        });

        $('.datepicker').datepicker();

        $('input[type=checkbox][name=profilegroup]').change(function () {
            checked = $(this).attr('checked');
            if (checked) {
                $('input[type=checkbox][name=profilegroup]').removeAttr('checked');
                $(this).attr('checked', 'checked');
            }
        });
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert('Failed to retrieve items, please try again.');
    },
    complete: function () {
        $('#loading').hide();
    }
});
}



function handleResolveProfileSelectionRequired() {
var valid = true;
var msg = '';

var notEmpty = /\S/

var transferEffectiveDate = $("#TransferEffectiveDate").val();
if (!notEmpty.test(transferEffectiveDate)) {
    msg += "Please select a transfer effective date.\r\n";
    valid = false;
}

var selectedGroup = $("select[name='profileGroups']").val();
if (selectedGroup == undefined || selectedGroup <= 0) {
    msg += "Please select a transferor profile group.\r\n";
}

if (!valid) {
    alert(msg);
} else {
    $.ajax({
        url: "/JobException/ResolveProfileSelectionRequired/",
        dataType: "json",
        traditional: true,
        type: "POST",
        data: {
            __RequestVerificationToken:       $('input[name=__RequestVerificationToken]').val(),
            JobId: $("#JobException_JobId").val(),
            TransferEffectiveDate: transferEffectiveDate,
            SelectedTransferorProfileGroupId: selectedGroup
        },
        beforeSend: function () {
            $('#loading').show();
        },
        success: function (result) {
            window.location.reload();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert('Failed to resolve profile selection required job exception, please try again.');
            window.location.reload();
        },
        complete: function () {
            $('#loading').hide();
        }
    });
}
}

function setJobExceptionDataTable() {
aoColumnsObject =
[
    {
        "sName": "JobId",
        "sType": "numeric",
        "fnRender": function (oObj) {

            var jobId = oObj.aData[0];
            var jobName = oObj.aData[1];
            var jobSubmitted = oObj.aData[2];
            var jobStatus = oObj.aData[3];

            return '<a href="/" class="detailsLink"' + '" jobid="' + jobId + '" jobname="' + jobName + '" jobstatus="' + jobStatus + '" jobsubmitted="' + jobSubmitted + '">' + jobId + "</a>";
        }
    },
    { "sName": "JobName" },
    { "sName": "JobSubmitted", "sType": "date" },
    { "sName": "JobStatus" }
];

var oTable = $("#orderQueueTable").dataTable({
    "bServerSide": true,
    "sAjaxSource": "/JobException/GetJobExceptionItems/",
    "bProcessing": false,
    "fnServerData": function (sSource, aoData, fnCallback) {
        aoData.push({ "name": "jobExceptionType", "value": $("#JobExceptionType").val()       });

        $.ajax({
            "dataType": 'json',
            "type": "GET",
            "url": sSource,
            "data": aoData,
            "beforeSend": function () {
                $("#loading").removeClass('invisible');
            },
            "success": fnCallback,
            "complete": function () {
                $(".detailsLink").live('click', function () {
                    getJobExceptionDetails($(this).attr('jobid'), $(this).attr('jobname'), $(this).attr('jobstatus'), $(this).attr('jobsubmitted'), $("#JobExceptionType").val());
                    return false;
                });

                $("#loading").addClass('invisible');
            }
        });
    },
    "aoColumns": aoColumnsObject,
    "iDisplayLength": 25,
    "bDestroy": true,
    "bJQueryUI": true,
    "sPaginationType": "full_numbers",
    "bAutoWidth": false
});
}

function setProfileSelectionRequiredDataTables() {
$("#orderInfoTable").dataTable({
    "bJQueryUI": true,
    "bAutoWidth": false,
    "bDestroy": true,
    "bSort": false,
    "bPaginate": false,
    "bFilter": false,
    "bInfo": false,
    "aoColumns": [
            null,
            null,
            { "sType": "date" },
            null
        ]
});

}

这是html:

@model MarylinMonroeMvcSite.Models.JobException.ProfileSelectionRequiredModel

<div class="float-left">Profile Selection Required Resolution</div>

<div class="float-right">Job Id: @Model.JobException.JobId</div>
<div class="clear"></div>
<br />

<form method="post" target="/JobException/ResolveProfileSelectionRequired"     id="profileSelectionResolutionForm">

@Html.AntiForgeryToken()

@Html.HiddenFor(x => x.JobException.JobId, new { value = Model.JobException.JobId })

<div>
    Job Id: @Model.JobException.JobId<br />
    Job Name: @Model.JobException.JobName<br />
    Job Submitted: @if (Model.JobException.JobSubmitted.HasValue)
    { @Model.JobException.JobSubmitted.Value.ToString("MM/dd/yyyy                 HH:mm:ss") }<br />
    Job Status: @Model.JobException.JobStatus
</div>

<br />

<div id="transferTypes">
    Select Transfer Type:
    <select name="tranTypes" id="tranTypes">
        <option value="0">Please Choose Transfer Type</option>
        @foreach (var type in Model.TransferTypes)
        {
            <option value="@type.TypeId">@type.TypeDescription</option>
        }
    </select>
</div>

<br />

<div>
    Transfer Effective Date: 
    @Html.TextBoxFor(x => x.TransferEffectiveDate, new { @class = "datepicker" })
</div>

<br />

<div id="transferorProfileGroups" class="invisible">
    Select Transferor Profile Group<br />
    <select name="profileGroups">
        <option value="0">Please Choose Group</option>
        @foreach (var group in Model.TransferorProfileGroups)
        {
            <option value="@group.GroupId">@group.DisplayName</option>
        }

    </select>
</div>

<div id="transfereeProfile" class="invisible">
    Select Transferee Profile Group <br />
    <select name="transfereeGroups">
        <option value="0">Please Choose Group</option>
        @foreach (var feree in Model.TransfereeList)
        {
            <option value="@feree.TransfereeListId">@feree.TransfereeName</option>
        }
     </select>
  </div>

<br />

<div>
    <input type="button" value="Submit" id="btnResolveProfileSelectionRequired" />
</div>

</form>
4

2 回答 2

1

当 DOM 完成加载时,像“live”、“click”这样的 jQuery 绑定将绑定到元素。任何 AJAX 响应的元素都不会绑定到它们。相反,您应该使用“.on”方法。

像这样:

$(document).on('click', '.my_new_element', function() {
    //your code here
});

这将起作用,因为“.on”绑定到文档而不是特定元素。由于第二个参数 ('#my_new_element') 是一个过滤器,因此 click 事件只会在对该元素执行时触发此函数。

因此,只要新的 HTML 元素通过带有“my_new_element”类的 AJAX 出现,它们就会在对它们执行事件时触发您的函数。

只是为了澄清:您不需要绑定到“文档”。您可以将“.on”方法绑定到任何保证在调用 AJAX 之前加载的元素。例如,您的所有网站都在 a<div class="content"></div>在这种情况下,您可以像这样绑定:

$('.content').on('click', '.my_new_element', function() {
    //your code here
});
于 2013-09-17T20:13:04.727 回答
0

我解决了这个问题,这是我没有看到的一个小问题。由于使用旧版本的 Jquery 我无法使用 .on ,所以我坚持使用 .live ,它工作得很好。我只是让我的 if 语句搜索值而不是标签。所以代码来自:

function handleTransferTypeSelection() {
$('#tranTypes').live('change' , function () {
var transfertypesvalue = $(this).val();

if (transfertypesvalue == "Transfer In") {
    $('#transferorProfileGroups]').removeClass('invisible');
    $('#transfereeProfile').addClass('invisible'); 

}
else if (transfertypesvalue == "Transfer Out") {
    $('#transfereeProfile').removeClass('invisible');
    $('#transferorProfileGroups').addClass('invisible');
}
else {
    $('#transfereeProfile').addClass('invisible');
    $('#transferorProfileGroups').addClass('invisible');
}
});
}

现在是:

function handleTransferTypeSelection() {
$('#tranTypes').live('change' , function () {
var transfertypesvalue = $('#tranTypes option:selected').text();
                                        // ^ ^ ^ ^ ^ ^ ^ ^ ^ the changes
if (transfertypesvalue == "Transfer In") {
    $('#transferorProfileGroups]').removeClass('invisible');
    $('#transfereeProfile').addClass('invisible'); 

}
else if (transfertypesvalue == "Transfer Out") {
    $('#transfereeProfile').removeClass('invisible');
    $('#transferorProfileGroups').addClass('invisible');
}
else {
    $('#transfereeProfile').addClass('invisible');
    $('#transferorProfileGroups').addClass('invisible');
}
});
}

小事使一切变得不同。

于 2013-09-20T15:15:52.680 回答