javascript - 如何在 MVC 中点击时获取 TD 的值

标签 javascript jquery asp.net-mvc asp.net-mvc-4 razor

我知道这个问题被问了很多,但我已经尝试了所有的 clickevents 但似乎无法让它工作我正在尝试从 td 获取值或字符串这是我构建的表

   <table id="tblMain">
  <thead>
    <tr>
        <th>Parcel ID</th>
        <th>Quick Ref ID</th>
        <th>Address</th>
        <th>Tax Unit</th>
        <th>Style</th>
        <th>Arch Style</th>
        <th>Validity Code</th>
        <th>Sale Price</th>
        <th>Sale Date</th>
        <th>Year Built</th>
        <th>Total Living Area</th>
        <th>Lot Area</th>
        <th>Bedrooms</th>
    </tr>
</thead>

<tbody>

    @foreach (var item in Model)
    {
        <tr class="side-link">


                <td class="parcelIDCell"><a id="Parcelid"    /> @item.ParcelId </td>
                <td>@item.QuickRefId</td>
                <td>@item.Address</td>
                <td>@item.TaxunitA</td>
                <td>@item.StyleA</td>
                <td>@item.ArchStyleA</td>
                <td>@item.ValCode</td>
                <td>@item.SalePriceA</td>
                <td>@item.SaleDateA</td>
                <td>@item.YearBuilt</td>
                <td>@item.LivingArea</td>
                <td>@item.LotArea</td>
                <td>@item.BedroomA</td>
                 @*<td>@item.ParcelID</td>
                <td>@item.PropertyID</td>*@

        </tr>
    }

</tbody>

我只想从第一行检索包裹 ID,具体取决于我点击的是哪一个 我试过的一些java脚本

 <script>
var tbl = document.getElementById("tblMain");
if (tbl != null) {
    for (var i = 0; i < tbl.rows.length; i++) {
        for (var j = 0; j < tbl.rows[i].cells.length; j++)
            tbl.rows[i].cells[j].onclick = function () { getval(this); };
    }
}

function getval(cel) {
    alert(cel.innerHTML);
}

还有很多但是我删掉了 任何建议将不胜感激

最佳答案

你想要一个 id 还是字符串?你可以这样做:

$("td").click(function() {
  if($(this).hasClass("parcelIDCell")){
  var ID = $(this).find("a").attr("id");
  alert("Id is: " + ID);
 }else{
   var String = $(this).text();
   alert("Text is: " + String);
 }
});

它检查被点击的 td 是否有 parcelIDCell 类,如果有,它会在其中找到 a 标签,然后拉取 id。如果该类不存在,它只会抓取文本。下面的 fiddle :

FIDDLE

关于javascript - 如何在 MVC 中点击时获取 TD 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27627153/

相关文章:

asp.net - oAuth ASP.NET 成员(member)提供商

javascript - 使用 CSS 设置 HTML5 自动对焦属性

jquery - 替换这个功能好像不起作用?

jquery - 执行函数不超过一次

c# - Mvc 3 如何列出所有可用路由?

jquery - ASP.NET MVC 中的 AJAX 表单提交模式

javascript - 加载时淡入图像

javascript - 完全禁用 DIV 中任何类型的垂直滚动

Javascript/JQuery 遍历数组值

javascript - 使用cherrypy和JavaScript的HTML进度条