当指定了选择器时,为什么jQuery.index()方法只适用于集合中的第一个元素
Why does the jQuery .index() method only work for the first element in the collection, when a selector is specified?
我正试图通过添加同一表的tfoot
中文本框字段的值来构建一个表。最终的目标是能够内联编辑以前添加的行,同时仍然可以添加更多的行。
我有以下标记:
<table>
<thead>
<tr>
<th>Service</th>
<th>Protocol</th>
<th>Source Port</th>
<th>Destination Port</th>
<th>Action</th>
</tr>
</thead>
<tfoot>
<tr>
<td>
<input type="text" data-function="service" value="foo" />
</td>
<td>
<input type="text" data-function="protocol" value="bar" />
</td>
<td>
<input type="text" data-function="sourcePort" value="baz" />
</td>
<td>
<input type="text" data-function="destPort" value="fob" />
</td>
<td>
<button id="addBtn" type="button">Add</button>
</td>
</tr>
</tfoot>
</table>
以下脚本将tfoot
中的所有input[type=text]
元素存储在输入变量中。从那里我尝试使用.index()
来识别并检索每个文本框的值:
$(document).ready(function () {
$('#addBtn').click(function (e) {
var inputs = $(this).closest('tfoot').find('input[type=text]');
console.log(inputs);
var serviceIndex = inputs.index('[data-function="service"]');
console.log(serviceIndex);
console.log(inputs[serviceIndex].value);
// the remaining indexes all return -1
var protocolIndex = inputs.index('[data-function="protocol"]');
console.log(protocolIndex);
console.log(inputs[protocolIndex].value);
var sourcePortIndex = inputs.index('[data-function="sourcePort"]');
console.log(sourcePortIndex);
console.log(inputs[sourcePortIndex].value);
var destPortIndex = inputs.index('[data-function="destPort"]');
console.log(destPortIndex);
console.log(inputs[destPortIndex].value);
});
});
不幸的是,选择器data-function="X"
选择器仅适用于服务。所有其他选择器返回-1
,指示未找到值。上面的代码来自这个jsFiddle,它说明了这个问题。我不习惯使用索引,但不能使用元素的id
,因为我需要一个更通用的解决方案。
当指定了选择器时,为什么jQuery.index()方法只适用于集合中的第一个元素?
来自文档:
如果对元素集合和DOM元素调用.index()或jQuery对象被传入,.index()返回一个整数,指示传递的元素相对于原始集合的位置。
所以这应该有效:
inputs.index($('[data-function="protocol"]'));
...
演示:http://jsfiddle.net/Dfxy9/2/
在使用它的上下文中,.index
仅在jQuery集合中的第一个元素上调用。jQuery对任何非迭代方法(例如.html
、.attr
、.text
)都是这样做的——.index
也不例外。
不要使用集合,而是使用选择器:http://jsfiddle.net/4kLqb/
相关文章:
- AddEventListener适用于浏览器,但不适用于Android
- 查找仅适用于原始图像的图像放大算法的名称
- 如何在category.php中执行jquery,这应该适用于类别wordpress中的每个帖子
- Web编程,简单但适用于机器人项目
- JavaScript不适用于internet explorer和Firefox,但适用于谷歌
- Jquery事件处理程序仅适用于匿名函数
- jQuery调整大小函数只适用于窗口
- 火灾在卸载前确认警报仅适用于外部站点
- EmberJS-适用于各种模型的适配器动态名称空间
- Facebook共享链接适用于用户,但不适用于粉丝页面管理员
- 使悬停菜单适用于移动设备的最佳实践方法是什么?
- 这个 Ajax 方法是否适用于许多浏览器和操作系统
- Javascript pub/sub 实现适用于函数,但不适用于对象的方法
- Facebook Canvas应用:这种方法只适用于游戏
- 将此变量传递给javascript方法的安全方法适用于所有浏览器
- 这种创建对象的方法是否只适用于单例对象?
- 寻找一种方法,使这种JS效果适用于我的页面上的所有文本,加载
- 当指定了选择器时,为什么jQuery.index()方法只适用于集合中的第一个元素
- Range.select() 等效方法,适用于非 IE 浏览器
- 有什么更好的方法来创建适用于多行的下拉列表