简体   繁体   English

使用 javascript 从跨度(不是文本)中获取值

[英]Grab the value from a span (not the text) using javascript

I am attempting to grab the value of a span attribute but am only successful so far in grabbing the text (which I don't need in this case).我正在尝试获取 span 属性的值,但到目前为止只成功获取了文本(在这种情况下我不需要)。

 // I want the value to return "10" myValue = document.querySelector(".count-total").getElementByID("data-multiply") console.log(myValue)
 <div class="count-total"> <span data-multiply="10">20 Doses</span> </div>

Target the span with querySelector , and then get the multiply value from the dataset .使用querySelector定位span ,然后从数据集中获取multiply值。

 const span = document.querySelector('.count-total span'); console.log(span.dataset); const val = span.dataset.multiply; console.log(val);
 <div class="count-total"> <span data-multiply="10">20 Doses</span> </div>

Use the dataset attribute: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset使用dataset属性: https : //developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset

 const node = document.querySelector(".count-total span[data-multiply]") console.info(node.dataset.multiply)
 <div class="count-total"> <span data-multiply="10">20 Doses</span> </div>

.getElementByID("data-multiply") is neither syntactically correct nor will it get the data attribute .getElementByID("data-multiply")在语法上既不正确,也不会获得数据属性

it is spelled getElementById but is used when an element has an ID它拼写为getElementById但在元素具有 ID 时使用

You need to use the querySelector with the complete path and use the dataset property您需要使用带有完整路径的 querySelector 并使用dataset 属性

 // I want the value to return "10" const myValue = document.querySelector(".count-total span").dataset.multiply; console.log(myValue)
 <div class="count-total"> <span data-multiply="10">20 Doses</span> </div>

getElementById (note the lower case d at the end) looks for an element with a matching id="xyz" value. getElementById (注意末尾的小写d )查找具有匹配id="xyz"值的元素。 None of your elements has an id .你的元素都没有id

Assuming the span with data-multiply is the only (or at least first) element with that data-* attribute, you can find it with querySelector using an attribute selector ( [data-multiply] ) and read its attribute value via getAttribute or dataset :假设带有data-multiplyspan是具有该data-*属性的唯一(或至少是第一个)元素,您可以使用属性选择器( [data-multiply] )通过querySelector找到它,并通过getAttributedataset读取其属性值:

 const element = document.querySelector("[data-multiply]"); const myValue = element.getAttribute("data-multiply"); console.log(myValue); const myValue2 = element.dataset.multiply; console.log(myValue2);
 <div class="count-total"> <span data-multiply="10">20 Doses</span> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM