成功克隆并附加后无法使用标识符访问 dom 元素
我准备了一个模板 div 的克隆,为其分配一个动态 ID 并将其附加到 DOM,如下所示:-
var chat_window_clone_obj = $('div#chat_window_template').clone();
cloned_element_id = 'chat_window'+dom_id_separator+session_id;
$(chat_window_clone_obj).attr('id',cloned_element_id);
$(chat_window_clone_obj).appendTo("div#chat_windows_holder");
但是,之后我无法使用其 ID 访问克隆元素(在 firefox 中检查过,我确信这将是在所有浏览器中都相同):-
$('div#chat_windows_holder').length // comes 0
$('div#chat_windows_holder').removeClass("hidden"); //does not work
但是我可以这样访问:-
$(chat_window_clone_obj).length // works
$(chat_window_clone_obj).removeClass("hidden"); //works
我在这里缺少什么?我可以在 Firefox 的 HTML 选项卡中看到该元素正确附加了所需的 ID。
I prepare a clone of a template div, assign it a dynamic ID and append it to DOM, like this:-
var chat_window_clone_obj = $('div#chat_window_template').clone();
cloned_element_id = 'chat_window'+dom_id_separator+session_id;
$(chat_window_clone_obj).attr('id',cloned_element_id);
$(chat_window_clone_obj).appendTo("div#chat_windows_holder");
But, after that I am not able access the cloned element using its ID (checked in firefox, I am sure this will be the same in all browsers):-
$('div#chat_windows_holder').length // comes 0
$('div#chat_windows_holder').removeClass("hidden"); //does not work
I am however able to access like this:-
$(chat_window_clone_obj).length // works
$(chat_window_clone_obj).removeClass("hidden"); //works
What am I missing here? I can see the element appended correctly with the required ID in firefox's HTML tab.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您尝试通过 ID 选择它时,您将获得原始元素 - 就像第一个与该 ID 匹配的元素一样。 文档中不应有重复的 ID 。试试这个:
When you try selecting it by ID, you're getting the original element - as in the first one which matches that ID. You should not have duplicate IDs in your document. Try this:
我认为问题是你没有通过正确的 ID 访问。 chat_windows_holder是新创建的对象的ID吗?它看起来不像在您的示例代码中。
chat_window_clone_obj 的值是多少?这就是您应该在选择器中使用的值(这就是第二个示例有效的原因)。
I think the problem is that your not accessing by the correct ID. Is chat_windows_holder the ID of the newly created object? It doesn't look like it is in your sample code.
What is the value of chat_window_clone_obj? That's the value you should be using in your selector (which is why the second example works).
好吧,问题是我在 dom id 中使用了一些非法字符,我将这些字符分配给新克隆的元素。
像这样的东西 -
检查 DOM ID 中允许使用哪些字符?< /a> 用于合法字符列表。
我正确分配了动态 ID。后来我用
$()
去掉了chat_window_clone_obj
的包装。Well guys the problem was that I was using some illegal characters in the dom id which I was assigning to the newly cloned elements.
Something like this -
Check What characters are allowed in DOM IDs? for list of legal characters.
I was correctly assigning dynamic IDs. I removed the wrapping of
chat_window_clone_obj
with$()
later.