【问题标题】:How to get the Id of Passed html element Using jQuery?如何使用 jQuery 获取传递的 html 元素的 ID?
【发布时间】:2011-06-17 06:40:31
【问题描述】:

我的列表页面中有这样的代码:

 <g:each in="${clientTripInstanceList}" status="i" var="clientTripInstance">
     <tr class="${(i % 2) == 0 ? 'odd' : 'even'}" id="${(i % 2) == 0 ? 'odd' : 'even'}">
         <td onclick="show_view('${clientTripInstance.id}')" class = "td_link">${fieldValue(bean: clientTripInstance, field: "number")}</td>
         <td onclick="show_view('${clientTripInstance.id}')" class = "td_link">${fieldValue(bean: clientTripInstance, field: "client")}</td>

      </tr>
</g:each>

现在

function show_view(trip_id){
   var rowId =           // get the id of the row

 }

从这个函数我需要得到上面指定的表格行的 id。我如何使用 jQuery 获得它?我试过这个:

var rowId = (this).attr("id"); 

这根本不起作用。请注意,我在 &lt;tr&gt; 中定义了 id 而不是在 &lt;td&gt; 我正在调用该函数的地方,并且该函数在其他页面中定义。

【问题讨论】:

  • var rowId =$(this).attr("id");美元符号

标签: javascript jquery grails groovy


【解决方案1】:

你忘记了美元符号:(

var rowId = $(this).attr("id");

编辑

<g:each in="${clientTripInstanceList}" status="i" var="clientTripInstance">
    <tr class="${(i % 2) == 0 ? 'odd' : 'even'}" id="${(i % 2) == 0 ? 'odd' : 'even'}">
        <td id="${clientTripInstance.id}" onclick="show_view('${clientTripInstance.id}')" class= "td_link">${fieldValue(bean: clientTripInstance, field: "number")}</td>
        <td onclick="show_view('${clientTripInstance.id}')" class= "td_link">${fieldValue(bean: clientTripInstance, field: "client")}</td>
    </tr>
</g:each>

function show_view(trip_id){
    var $this = $('#' + trip_id);
    var row_id = $this.parent().attr('id');
}

【讨论】:

  • 如果我的编辑有帮助,请告诉我。我在第一个 td 中添加了一个 id 属性,我认为以后需要访问它。
  • 我用不同的方式完成了 ${fieldValue(bean : clientTripInstance, field: "number")} 然后改变函数如 ... function show_view(element,trip_id){ var rowId = $(element).closest("tr").attr("id" ); }
  • 请提供更多帮助!如何使用 jquery 获取下一个 的 id?
  • 从前面的tr 呢? $('#foo').next();其中#foo 是一个 tr。如果它后面没有另一个兄弟,这将返回undefined
【解决方案2】:

要在 show_view() 中引用您单击的表格单元格,您可以将 'this' 参数传递给函数,试试这个:

<td onclick="show_view(this, '${clientTripInstance.id}')" class = "td_link">${fieldValue(bean: clientTripInstance, field: "number")}</td>

function show_view(dom, trip_id) {
    var rowId = $(dom).parent().attr("id");
}

【讨论】:

  • 请提供更多帮助!如何使用 jquery 获取下一个 的 id?
  • 您可以通过检查 API 轻松获得答案:api.jquery.com/browser
【解决方案3】:

你也可以使用:

var rowId = this.id

这只是 javascript,不是 jQuery

【讨论】:

  • +1 有时直接的 javascript 方式是最好的方式 - 尽管在这种情况下“this”有点模棱两可。
  • 你能给出确切的答案吗?
  • 请提供更多帮助!如何使用 jquery 获取下一个 的 id?
猜你喜欢
相关资源
最近更新 更多
热门标签