如何使用带有Variable的Jquery Id选择

时间:2016-02-20 01:25:28

标签: javascript jquery razor

所以我的脚本中有一个部分如下所示:

$('input[id="TestMyId"]').autocomplete({
    source: availableChoice
 },
});

这很好用,我可以自动完成自动完成功能,我可以从一个选项列表中进行选择,但是当我将Test变为一个字符串变量并尝试将它与MyId连接时,我根本无法触发:

@{
    var foo = "Test";
}
<body..../>
<script>
    $('input[id="' + @foo + 'MyId"]').autocomplete({
        source: availableChoice
     },
    });
</script>

foo被声明为.cshtml中的全局变量。当我连接名称时,不确定为什么Id选择不起作用?任何帮助都会很感激。

好的我已经在下面发布了更多细节,在这个测试用例中Id是FirstNameId,试图将它与@prefix变量结合起来:

    @using System.Collections.Concurrent
    @model MyModel

    @{
        var prefixt = "TestContactInformation";
    }

    @using (Html.BeginForm("MyAction", "MyController"))
    {

    <article class="widget widgetFullPage" data-role="collapsible" data-collapsed="true" id="articlePrimaryContact" style="height:auto">
        <h2>Test Information</h2>

        <table id="tableContactInformation">
            <tr>
                <td style="width: 180px; padding-top: 20px; padding-left: 15px;"><label>Relationship to Policyholder</label></td>
                <td style="width: 50px; padding-top: 15px">@Html.DropDownListFor(x => x.PrimaryContact.ContactRole, (List<SelectListItem>)ViewBag.RelToPolicyList, new { id = @prefixt + "RoleId", style = "width:130px", tabindex = @tabIndexBase + 1 })</td>
                <td style="width: 100px; padding-top: 20px; padding-left: 15px;" id=" titlelable"><label>Title</label></td>
                <td style="width: 200px; padding-top: 20px;padding-left: 12px;" id="TitleText">@Html.TextBoxFor(x => x.PrimaryContact.Title, null, new { id = @prefixt + "TitleId", style = "width:250px", tabindex = @tabIndexBase + 8 })</td>
            </tr>
            <tr id=@prefixt>
                <td style="width: 150px; padding-left: 15px;"><label>Contact Description</label></td>
                <td style="width: 100px">
                    @Html.TextBoxFor(x => x.PrimaryContact.ContactRoleDescription, null, new { id = @prefixt + "DescriptionId", style = "width:250px", tabindex = @tabIndexBase + 2 })
                </td>
            </tr>
            <tr style="height: 30px;">
                <td style="width: 100px; padding-left: 15px;">
                    <label>First Name</label>
                    @if (@prefixt == "TestContactInformation")
                    {
                        <a id="LearnMore"><img src="~/Images/info.png" alt="" /></a>
                    }
                </td>
                @*<td style="width: 100px;">@Html.TextBoxFor(x => x.PrimaryContact.FirstName, null, new { id = @prefixt + "FirstNameId", style = "width:250px", tabindex = @tabIndexBase + 3 })</td>*@
                <td style="width: 100px;">@Html.TextBoxFor(x => x.PrimaryContact.FirstName, null, new { id = @prefixt + "FirstNameId", style = "width:250px", tabindex = @tabIndexBase + 3 })</td>
                <td style="width: 100px;padding-left: 15px;"><label>Address Line 1</label></td>
                <td style="width: 200px;padding-left: 12px;">@Html.TextBoxFor(x => x.PrimaryContact.AddressLine1, null, new { id = @prefixt + "Address1Id", style = "width:250px", tabindex = @tabIndexBase + 9 })</td>
            </tr>
            <tr style="height: 30px;">
                <td style="width: 100px;  padding-left: 15px;"><label>Last Name</label></td>
                <td style="width: 100px; ">@Html.TextBoxFor(x => x.PrimaryContact.LastName, null, new { id = @prefixt + "LastNameId", style = "width:250px", tabindex = @tabIndexBase + 4 })</td>
                <td style="width: 100px;  padding-left: 15px;"><label>Address Line 2</label></td>
                <td style="width: 200px; padding-left: 12px;">@Html.TextBoxFor(x => x.PrimaryContact.AddressLine2, null, new { id = @prefixt + "Address2Id", style = "width:250px", tabindex = @tabIndexBase + 10 })</td>
            </tr>
            <tr style="height: 30px;">
                <td style="width: 100px;  padding-left: 15px;"><label>Email</label></td>
                <td style="width: 100px; ">@Html.TextBoxFor(x => x.PrimaryContact.Email, null, new { id = @prefixt + "EmailId", style = "width:250px", tabindex = @tabIndexBase + 5 })</td>
                <td style="width: 100px;  padding-left: 15px;"><label>City</label></td>
                <td style="width: 200px; padding-left: 12px;">@Html.TextBoxFor(x => x.PrimaryContact.City, null, new { id = @prefixt + "CityId", style = "width:250px", tabindex = @tabIndexBase + 11 })</td>
            </tr>
            <tr style="height: 30px;">
                <td style="width: 100px;  padding-left: 15px;"><label>Phone</label></td>
                <td style="width: 100px; ">@Html.TextBoxFor(x => x.PrimaryContact.Phone, null, new { id = @prefixt + "PhoneId", @class = "phone", style = "width:250px", tabindex = @tabIndexBase + 6 })</td>
                <td style="width: 100px; padding-left: 15px;"><label>State</label></td>
                <td style="width: 200px; padding-left: 12px;">@Html.DropDownListFor(x => x.PrimaryContact.State, Model.PrimaryContact.StatesList ?? (List<SelectListItem>)ViewBag.StatesList, new { id = @prefixt + "StateId", style = "width:130px", tabindex = @tabIndexBase + 12 })</td>
            </tr>
            <tr style="height: 30px;">
                <td style="width: 100px;  padding-left: 15px; padding-bottom: 20px"><label>Ext.</label></td>
                <td style="width: 100px;padding-bottom: 20px">@Html.TextBoxFor(x => x.PrimaryContact.Ext, null, new { id = @prefixt + "ExtId", style = "width:250px", @class = "numbersOnly", tabindex = @tabIndexBase + 7 })</td>
                <td style="width: 100px;  padding-left: 15px;padding-bottom: 20px"><label>Zip</label></td>
                <td style="width: 200px;padding-left: 12px;padding-bottom: 20px">@Html.TextBoxFor(x => x.PrimaryContact.Zip, null, new { id = @prefixt + "ZipId", @class = "zip", style = "width:250px", tabindex = @tabIndexBase + 13 })</td>
            </tr>
        </table>
    </article>

    }

    <link rel="stylesheet" href="~/Content/jquery-ui.css" />
    <style>
        .ui-corner-all,
        .ui-corner-top,
        .ui-corner-left,
        .ui-corner-tl {
            border-top-left-radius: 0;
        }

        .ui-corner-all,
        .ui-corner-top,
        .ui-corner-right,
        .ui-corner-tr {
            border-top-right-radius: 0;
        }

        .ui-corner-all,
        .ui-corner-bottom,
        .ui-corner-left,
        .ui-corner-bl {
            border-bottom-left-radius: 0;
        }

        .ui-corner-all,
        .ui-corner-bottom,
        .ui-corner-right,
        .ui-corner-br {
            border-bottom-right-radius: 0;
        }
    </style>

    <script type="text/javascript">
        var availableContacts = [];

        @foreach (var theContact in Model.ContactsList)
        {
            @:availableContacts.push( {value: "@theContact.FirstName, @theContact.LastName, @theContact.City, @theContact.State", label: "@theContact.FirstName, @theContact.LastName" });
        }

        //$("input[id='TestContactInformationFirstNameId']").autocomplete({
        //    source: availableContacts,
        //    select: function (event, ui) {
        //        var firstName = ui.item.value.split(',')[0];
        //        var lastName = ui.item.value.split(',')[1];
        //        var city = ui.item.value.split(',')[2];
        //        var state = ui.item.value.split(',')[3];
        //        alert(firstName);
        //        alert(lastName);
        //        alert(city);
        //        alert(state);
        //    },
        //});

        var theConcated = @string.Format("{0}FirstNameId", @prefixt);
        $("input[id='" + theConcated + "']").autocomplete({
            source: availableContacts,
            select: function (event, ui) {
                var firstName = ui.item.value.split(',')[0];
                var lastName = ui.item.value.split(',')[1];
                var city = ui.item.value.split(',')[2];
                var state = ui.item.value.split(',')[3];
                alert(firstName);
                alert(lastName);
                alert(city);
                alert(state);
            },
        });

    </script>
    <script type="text/javascript" src="~/Scripts/jquery.maskedinput.js"></script>

带有

的注释部分
$("input id='TestContactInformationFirstNameId']") 

效果很好,但运行带有我得到的组合字符串的其他部分是:

0x800a1391 - JavaScript runtime error: 'TestContactInformationFirstNameId' is undefined

任何想法?

2 个答案:

答案 0 :(得分:0)

这个选择器在jQuery中不具备性能。您应首先使用ID选择器,然后使用过滤器函数应用输入约束(如果甚至是必要的,因为ID应该是唯一的)。

$('#' + @string.Format("'{0}'", foo) + 'MyId').filter('input');

如果您正在做好事,意味着每页保持ID属性的唯一性,那么以下内容应该有效。

$('#' + @string.Format("'{0}'", foo) + 'MyId').autocomplete({
    source: availableChoice
 });

答案 1 :(得分:0)

好的,经过多次试验和错误后发现以下内容适用于我的案例,在此发帖可能会对其他人有所帮助:

$("input[id='@prefixt" + "FirstNameId']")

或者

$("#@prefixt" + "FirstNameId")

两者似乎都有效,看起来变量调用需要在引号内。