[英]get data-value with variable value
I have a data-value
in my php code that is used in several places, for example:我的 php 代码中有一个
data-value
,用于多个地方,例如:
<a class="dropdown-item" data-value="<?= $i ?>"></a>
<a class="dropdown-item" data-value="<?= $k ?>"></a>
And now I need to use one of these values in the script而现在我需要在脚本中使用这些值之一
getAttribute('data-value')
But I can't just use data-value
, since it will be relevant to everything that I have, I only need to use this data-value="<?= $k ?>"
但我不能只使用
data-value
,因为它与我拥有的一切相关,我只需要使用这个data-value="<?= $k ?>"
How can I specify a value with this variable in the script?如何在脚本中使用此变量指定值?
since you want to get the data-value of a specific element with the $k variable, your best bet is giving an id to that specific element and selecting it by id:由于您想使用 $k 变量获取特定元素的数据值,因此最好的选择是为该特定元素提供 id 并通过 id 选择它:
HTML HTML
<a id="element_with_k" class="dropdown-item" data-value="<?= $k ?>"></a>
JS JS
const elementWithK = document.getElementById('element_with_k');
elementWithK.dataset.value // "the content of $k"
In case thete are multiple elements that you want to select then you add an extra class to those elements, query all the elements that have the extra class , loop through them and get each element's value.如果您要选择多个元素,则向这些元素添加一个额外的类,查询具有额外类的所有元素,遍历它们并获取每个元素的值。
Hope this helps, cheers!希望这会有所帮助,干杯!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.