[英]how to retrieve the ID of the Link in Jquery?
我在這里遇到一種情況...請考慮以下情況
1)來自數據庫的值,例如:personName(數據庫中的whos id為3)
2)我正在通過@ Html.ActionLink鏈接“ personName”
3)鏈接ID為“ lnkName”
我想檢索單擊lnkName時personName的ID為3。 請幫我 ..
這是我的鏈接代碼。
@foreach (var item in Model)
{
<h3> @Html.ActionLink(item.personName, "Details", "Post", new { Id = item.personID } , new { @id = "lnkName" } ) </h3>
這是到目前為止我得到的Jquery代碼...
$(document).ready(function () {
$('#lnkName').click(function () {
$.ajax({
url: @Url.Action("AddViews","Post")
data: // how can i retrieve the id of the clicked link which is 3
});
});
});
以應有的方式生成鏈接,直接在href屬性中包含正確的url。 這樣,您無需擔心:
@Html.ActionLink(
item.personName,
"AddViews", // <!-- modify the action so that it directly points to the correct one
"Post",
new { id = item.personID },
new { @class = "lnkName" } // <!-- Notice that I use a class here instead of an id because ids must be unique in the DOM and in your code you have multiple links with the same id resulting into invalid markup
)
然后在一個單獨的javascript文件中,您可以毫不客氣地AJAXify這個錨點:
$(document).ready(function () {
$('.lnkName').click(function () {
$.ajax({
url: this.href,
success: function(result) {
}
});
// that's important in order to cancel the default action
// or the browser will simply redirect to the url and the AJAX
// call will never have time to execute
return false;
});
});
這樣,您可以將javascript放在應該完全獨立的js文件中。 當然,它的好處是可以將其縮小,壓縮,緩存甚至從CDN提供服務。 始終嘗試將javascript放在單獨的文件中,並根據服務器端表達式(例如@Url.Action
避免使用它們。 我已經向您展示了一種避免這種不希望的依賴的方法。
單擊鏈接后,可以通過this
變量獲取其id
:
$(document).ready(function () {
$('#lnkName').click(function () {
var id = this.id; // <=== you can fetch the id of the clicked link via "this"
$.ajax({
url: @Url.Action("AddViews","Post"),
data: id
});
return(false);
});
});
如果不是您想要的CSS ID(我不確定您的問題),而是其他一些數據(例如personID),則應將其他數據作為數據屬性放置在鏈接標記上並獲取jQuery使用$(this).data("xxx")
該屬性。
例如,如果服務器端代碼生成的鏈接如下所示:
<a href="xxx" class="lnkName" data-personID="3">
然后,在您的點擊處理程序中,您可以像這樣獲取該personID(然后,您必須將其放入ajax參數中,但要發送它):
$(document).ready(function () {
$('#lnkName').click(function () {
var personID = parseInt($(this).attr("data-personID"), 10); // <===
$.ajax({
url: @Url.Action("AddViews","Post"),
data: personID
});
return(false);
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.