gpt4 book ai didi

asp.net - 需要 JQuery 重构帮助

转载 作者:行者123 更新时间:2023-12-01 04:31:22 25 4
gpt4 key购买 nike

这是我的 JavaScript 代码:

<script type="text/javascript">
$(document).ready(function() {

var currentInput = '';
var currentLabel = '';

$("#userLookup").click(function() {
var url = "<%= Url.Action( "ListAll" , "User") %>";
currentInput = $("#User");
currentLabel = $("#lblUser");
openModal(url);
return false;

});

$("#locationLookup").click(function() {
var url = "<%= Url.Action( "ListAll" , "Location") %>";
currentInput = $("#Location");
currentLabel = $("#lblLocation");
openModal(url);
return false;
});


$(".selectable").live("click", function(e){
currentInput.val($(this).attr('id'));
var labelText = $(this).parent().parent().find('td').eq(2).html();
currentLabel.html(labelText);
$.fn.colorbox.close();
e.preventDefault();
});

});

function openModal(url){
$.fn.colorbox({
href:url
, open:true
, width: "400px"
, height: "300px"
});
}
</script>

这是我的 HTML

<table width = "100%">
<tr>
<td>Asset User Id:</td>
<td><%= Html.TextBox("User", Model.User, (object)new{style = "width:100px", maxLength="20"})%>
<a id="userLookup" href="#">Lookup User</a>
<label id="lblUser"></label>
<%=Html.ValidationMessage("User")%></td>
</tr>
<tr>
<td>Location Id:</td>
<td><%= Html.TextBox("Location", Model.Location, (object)new{style = "width:100px", maxLength="20"})%>
<a id="locationLookup" href="#">Lookup Location</a>
<label id="lblLocation"></label>
<%=Html.ValidationMessage("Location")%></td>
</tr>
</table>

我还有很多类似于上面列出的两个查找字段(我省略了),我想看看是否有人可以帮助我想出一种更干净/干燥的方法来完成这样的事情?

谢谢

最佳答案

我会将模式框的 url 添加到链接本身中。然后,您只需向该链接添加一个类即可调用所需的功能。这也意味着您可以将 JS 放在外部文件中,并且您的 JS 不依赖于 ASP.NET MVC Html 帮助器方法。

将您的 html 更改为:

<table width = "100%">
<tr>
<td>Asset User Id:</td>
<td>
<%= Html.TextBox("User", Model.User, (object)new{style = "width:100px", maxLength="20"})%>
<%= ActionLink("Lookup User", "ListAll", "User", null, new { class="lookup-link" }) %>
<label id="lblUser"></label>
<%=Html.ValidationMessage("User")%>
</td>
</tr>
<tr>
<td>Location Id:</td>
<td>
<%= Html.TextBox("Location", Model.Location, (object)new{style = "width:100px", maxLength="20"})%>
<%= ActionLink("Lookup Location", "ListAll", "Location", null, new { class="lookup-link" }) %>
<label id="lblLocation"></label>
<%=Html.ValidationMessage("Location")%>
</td>
</tr>
</table>

然后你可以将 jQuery 简化为:

var currentInput = '';
var currentLabel = '';

$(".lookup-link").click(function() {
var url = $(this).attr("href");
currentInput = $(this).siblings("input")[0];
currentLabel = $(this).siblings("label")[0];
openModal(url);
return false;
});

我还没有测试过这段代码,所以可能有一百万个错误。 ;-)

HTH,
查尔斯

关于asp.net - 需要 JQuery 重构帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2224102/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com