Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/434.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在jQuery中,如何选择节点(仅使用字符串选择器)";“开始”;从当前元素开始?_Javascript_Jquery - Fatal编程技术网

Javascript 在jQuery中,如何选择节点(仅使用字符串选择器)";“开始”;从当前元素开始?

Javascript 在jQuery中,如何选择节点(仅使用字符串选择器)";“开始”;从当前元素开始?,javascript,jquery,Javascript,Jquery,在下面的循环中,我想选择相对于当前元素$this的任意节点。选择器是一个字符串,存储在数据数量字段中: $('[data-add-product][data-qty]').each(function () { var $this = $(this), qtySelector = $this.data('qty'); // Here, i want to use the string selector "qty" // to select any

在下面的循环中,我想选择相对于当前元素
$this
的任意节点。选择器是一个字符串,存储在
数据数量
字段中:

$('[data-add-product][data-qty]').each(function () {
  var $this = $(this),
        qtySelector = $this.data('qty');

  // Here, i want to use the string selector "qty"
  // to select any arbitrary node, relative to the current element
  $this.parent().find(qtySelector); // not a good solution

});
我不能在
$this
上使用
parent()

例如:

<div>
  <a data-add-product="123546" data-qty=":parent .qty">Add to cart</a>
  <span class="qty">3</span>
</div>

添加到购物车
3.
类似的东西

document.querySelectorAll(“[数据添加产品][数据数量]”).forEach(el=>
{
设el_target=el.dataset.qty
.拆分(“”)
.减少((r,s)=>
{
如果(s==':parent')返回r.parentNode
如果(s[0]='.')返回r.querySelector
},el)
log(el_target.textContent,`\n`,el_target)
})

添加到购物车
3.

我不明白你的问题,你想从'data qty=“:parent.qty”``开始获取
3
上的值,谢谢你的回复。其目的是允许使用泛型选择器,因为我事先不知道其结构。您为什么需要将jQuery选择器放在HTML中?当然HTML不太可能改变。只需使用
$(this).sides('.qty')
..@Rorymcrossan可能在2或3个点中使用,其中html结构非常不同,您需要复制JS代码来做相同的事情。在这种情况下,请在UI中围绕该功能创建一个通用的、重复的html结构。谢谢,我会尝试,这正是我的意思,允许通用和灵活的选择器,因为我不知道html结构。