jquery - 用下一个 onLoad 的 id 替换 this 的内容
问题描述
给定下表,第一个<td>
的内容应该替换为下一个td.input
(id
拆分id后的第二个值)。
<table>
<colgroup>
<col width="100" />
<col width="100" />
</colgroup>
<tbody>
<tr>
<td>Element</td>
<td>Value</td>
</tr>
<tr>
<td><span>one</span></td>
<td id="test"><span><input id="rjaxWMQBmoH-HllvX50cXC0-val" name="entryfield" title="element" value="[ one ]" /></span></td>
</tr>
</tbody>
</table>
这样第一个<td>
就变成<td><span>HllvX50cXC0</span></td>
了负载。我可以看到$(this).next()
下面列出的方法,lastChildren
但我想知道这是否是正确的方法?
解决方案
你的问题和你的标记有几个方面,这使得这有点不太清楚,但下面评论的 jQuery 可以满足你的要求。
// no-conflict-safe document ready
jQuery(function($) {
// loop through all inputs contained inside of a td
$('td input').each(function() {
// load the id of the input
var id = $(this).attr('id');
// if the id exists, and has a - in it, then....
if (id && id.indexOf('-') > 0) {
// split the id into parts (regex would also work here)
id = id.split('-');
// get the second part of the id
id = id[1];
// put the id into the previous cell's contents
$(this).closest('td').prev('td').find('span').text(id);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<colgroup>
<col width="100" />
<col width="100" />
</colgroup>
<tbody>
<tr>
<td>Element</td>
<td>Value</td>
</tr>
<tr>
<td><span>one</span></td>
<td id="test"><span><input id="rjaxWMQBmoH-HllvX50cXC0-val" name="entryfield" title="element" value="[ one ]" /></span></td>
</tr>
</tbody>
</table>
有几种方法可以切片,这只是一种。
jQuery 的关键是使用好的选择器,以及对首选 DOM 导航功能的清晰理解。我强烈推荐最接近和查找(而不是parent或parents and children,它们有通过使用最接近 / find 避免的陷阱)。
推荐阅读
- android - 为什么 android 8.1 及更低版本的用户无法在 Play 商店中看到我的应用
- html - 创建并对齐 2 个 html 表
- symfony - 为什么 Doctrine 试图通过关系插入新实体?
- python - pandas groupby 应用返回一个数据框
- apache-kafka - kafka-run-class 抛出 java.lang.OutOfMemoryError 错误
- django - 在 django 模板的下拉列表中显示已选择的项目
- c++ - 如何在 Rcpp / C++ 中将函数作为参数传递?
- javascript - 如何在现有的 node.js express 设置中集成 rate-limiter-flexible?
- nix - 通过 Docker 构建时,如何缓存 nix 派生的依赖项?
- android - 为什么 Android Studio 抱怨 getApplicationContext()?