[英]How to get all li element to calculate using JavaScript
This list was generated using input tag and appending the element to ul : 此列表是使用输入标记生成的,并将元素附加到ul:
<ul id ="add">
<li>3</li>
<li>4</li>
<li>*</li>
<li>5<li>
<li>+<li>
<li>3</li>
<ul>
This is list now I would like to iterate over it so that on the console I get 34*5+3 which can calculate using JavaScript, but how to get the value of all Li to tag together so that it is able to calculate: 这是列表现在我想迭代它,以便在控制台上我得到34 * 5 + 3可以使用JavaScript计算,但如何获得所有Li的值来标记在一起,以便它能够计算:
The complete code is from which I would like to do the calculation : 完整的代码是我想要计算的:
<!DOCTYPE html>
<html>
<head>
<title>solve</title>
<script>
document.addEventListener('DOMContentLoaded',()=>{
document.querySelector('#submit').onclick =()=>{
const li = document.createElement('li');
li.innerHTML = document.querySelector('#number').value;
document.querySelector('#add').append(li);
return false;
};
});
</script>
<style>
li{
list-style-type: none;
display: inline;
}
</style>
</head>
<body>
<div id="user-input">
<ul id="add">
</ul>
</div>
<div>
<form>
<input type="text" id="number">
<input type="submit" id="submit">
</form>
</div>
</body>
</html>
You can use document.querySelector
and textContent
to get the text which will be a string then use eval
to calculate it. 您可以使用document.querySelector
和textContent
来获取将成为字符串的文本,然后使用eval
来计算它。
let m = [...document.querySelector("#add").children]; let val = ''; m.forEach(function(item) { val += item.textContent; }) console.log(eval(val)) //34*5+3
<ul id="add"> <li>3</li> <li>4</li> <li>*</li> <li>5</li> <li>+</li> <li>3</li> </ul>
You could iterate over the li's using forEach()
: 你可以使用forEach()
迭代li的:
var satatement = ''; document.querySelectorAll('#add li').forEach(function(item) { satatement += item.textContent.trim(); }); console.log(satatement, '=', eval(satatement));
li { list-style-type: none; display: inline; }
<div id="user-input"> <ul id="add"> <li>3</li> <li>4</li> <li>*</li> <li>5</li> <li>+</li> <li>3</li> </ul> </div>
let text = document.querySelectorAll('#add li').reduce((text, el) => text + el.innerHTML);
document.querySelectorAll('#add li')
to get the list items. 使用document.querySelectorAll('#add li')
获取列表项。 reduce
the results to a single string by concatenating all the elements' innerHTML
properties. 通过连接所有元素的innerHTML
属性将结果reduce
为单个字符串。 Of course you could also use the textContent
of the list, which includes 当然你也可以使用列表的textContent
,其中包括
the text content of a node and its descendants 节点及其后代的文本内容
document.querySelector('#add').textContent
, but that would include newlines between each li
. document.querySelector('#add').textContent
,但是包含每个li
之间的换行符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.