javascript - 我如何在 jQuery 中做到这一点?在 $ 中传递选择器而不是 jQuery 对象的任何技巧

标签 javascript jquery html

在 JavaScript 中,如果我将一个具有 ID 的子项附加到另一个位置,那么它将从它们当前所在的原始位置中删除。

在 javascript 中,我有一个事件,我可以通过在函数内使用它来获取选择器

$('.').event(function(){
    this
});

这被传递给另一个函数并且它们工作正常。现在我想传递克隆而不是对象;请记住,这没有 ID。

旧代码的工作原理是传递 this 来充当 DoSomething(this)

如果我使用 jQuery clone 进行克隆,那么我就有了 jQuery 对象。那么,在使用克隆时,如何获取对 this 的引用而不是 jQuery 对象呢?

var clone = $(this).clone() // this is jQuery object. 
//how do I get this out of clone? 

最佳答案

if I append a child which has an ID to another place then it's removed from original location where they currently are.

是的,但是对于没有 id 属性的子节点也是如此。 id 只是一种获取 Element 节点对象引用的简单方法;它对克隆行为的 DOM 插入没有影响。

In javascript I have an event where I can get selector by using this inside the function

不,事件处理程序中的 this 为您提供 DOM 元素节点对象,而不是选择器字符串。可以使用 $(node) 将节点转换为围绕其的 jQuery 包装器,并且可以使用 $(selector) 将选择器转换为匹配节点列表上的 jQuery 包装器> 但除了 jQuery API 中的重载之外,它们是完全不同的动物。

要将节点从 jQuery 包装器中拉出来,您可以使用 get()方法或简单的类似数组的访问:

var clonedNode= $(this).clone()[0];

var clonedNode= $(this).clone().get(0);

品尝。 (get() 有一些您不需要的额外功能。)

要获取用于创建 jQuery 包装器的选择器,您可以使用 selector属性,但如果包装器是从节点对象 ($(this)) 而不是选择器创建的,则不会返回任何内容。

关于javascript - 我如何在 jQuery 中做到这一点?在 $ 中传递选择器而不是 jQuery 对象的任何技巧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6174277/

相关文章:

javascript - 如何使引导导航栏在小屏幕上从右到左顺利切换 chrome?

javascript - 为什么通用 CSS 选择器 (*) 会覆盖内联样式?

html - 为什么 Vertical Align 在 jsfiddle 上工作

html - 如何让选择/下拉列表中的外来字符在 IE 7 中正确显示?

javascript - Angular 配置 es6 语法

javascript - 循环遍历数组,直到找到值,然后中断

jquery - 无法使用 jQuery 淡出子菜单

html - Bootstrap : How to close an open collapsed navbar when clicking outside of the MENU?

javascript - 为什么我的 JavaScript cookie 只能在一页上工作?

Javascript计算函数不计算