简体   繁体   English

获取跨度标签HTML的值

[英]Get a value of span tag HTML

my span tag looks like this: 我的span标签看起来像这样:

<span id="quantity_value" value="1">1</span>

And the value changes by using jquery. 并使用jquery更改值。

I want to have value of this span as a parameter, when i try with js script: 当我尝试使用js脚本时,我想将此范围的值作为参数:

var number = document.getElementById("quantity_value");

My number is equal to: 我的电话号码等于:

'<span id="quantity_value" value="1">1</span>'

But I want number to be equal to value. 但我希望数字等于价值。

If you add: 如果添加:

console.log(number); just after you define it, and look at the debugger, you'll see it has various properties. 在定义它并查看调试器之后,您将看到它具有各种属性。

You want to get the innerHTML , property: 您要获取innerHTML属性:

number.innerHTML

Use 采用

var number = document.getElementById("quantity_value").innerHTML;

By writing only 只写

var number = document.getElementById("quantity_value");

you store object in variable. 您将对象存储在变量中。

I would suggest changing value to a data field to fix your non-standards compliant html, and then you can retrieve that attribute when you need the value. 我建议将value更改为数据字段以修复不符合标准的html,然后在需要该值时可以检索该属性。 For instance: 例如:

 $('#changeValue').on('click', function(){ var newValue = Date.now() % 100; //change the data attribute $('#quantity_value').text(newValue).data('value', newValue); }); $('#getValue').on('click', function(){ console.log($('#quantity_value').data('value')); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <span id="quantity_value" data-value="1">1</span> <div><button id="changeValue">Change Value</button></div> <div><button id="getValue">Get Value</button></div> 

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

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