【问题标题】:I can not seem to select a dynamicaly generated tr by id[array]我似乎无法通过 id[array] 选择动态生成的 tr
【发布时间】:2013-02-10 22:38:58
【问题描述】:

我有一组由 ajax 调用 php 脚本生成的元素。

<tr id="rem[313]">...</tr>
<tr id="rem[345]">...</tr>

我的一个函数需要通过 id 删除某个 tr。

我已经尝试了所有方法,但似乎无法选择该死的东西

function remove_it(x){
$('#rem['+x+']').remove();
$(this).closest('tr').remove; // this i fire from the button click
}

测试我正在使用 .length 的选择,它都返回零

function remove_it(x){
alert($('#rem['+x+']').live().length;
alert($('#rem['+x+']').length);
alert($('#rem['+x+']').on().length);
} 

【问题讨论】:

  • 我支持大卫。特别是因为您使用双引号。或者使用单引号。
  • 您可能需要考虑将该 id 添加到 data-* 属性中。这将消除转义选择器内容的需要......您只需搜索$("tr[data-foo='"+ x +"']")

标签: jquery select dynamic


【解决方案1】:

要选择这个元素:

<tr id="rem[313]">...</tr>

用途:

$('#rem\\[' + x + '\\]')

Simple JS Fiddle proof-of-concept.

或者,您可以简单地使用:

$('tr[id^="rem"][id*="' + x + '"]');

Simple JS Fiddle proof-of-concept.

【讨论】:

  • 我必须将数组索引作为函数中的变量传递 - x 那么我 $('rem\['+x+'\]') 会吗?
  • 很好,转义成功了!!谢谢!!为什么我需要转义括号?必须等待 7 分钟才能接受答案。
  • 因为它们在 jQuery 选择器和 CSS 中用于属性等于、属性包含和属性存在表示法。
猜你喜欢
  • 1970-01-01
  • 2023-03-11
  • 2021-12-23
  • 1970-01-01
  • 2011-06-15
  • 1970-01-01
  • 2014-10-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多