属性访问器和dom元素的获取、遍历、增加

访问器属性 计算商品价格

  1. let shop = {
  2. data: [{
  3. id: 1,
  4. name: "西红柿",
  5. price: 2,
  6. quantity: 0
  7. }],
  8. get price() {
  9. return this.data[0].price;
  10. },
  11. set price(num) {
  12. this.data[0].quantity = num;
  13. let sum = this.data[0].price * num;
  14. this.data[0].price = sum;
  15. }
  16. }
  17. shop.price = 30;
  18. console.log(`购买了${shop.data[0].quantity}个西红柿,一共${shop.price}元!`);
  19. // 打印输出:购买了30个西红柿,一共60元!
  20. </script>

dom元素的获取、遍历、增加

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title></title>
  6. </head>
  7. <body>
  8. <ul id="list">
  9. <li>第1行</li>
  10. <li>第2行</li>
  11. <li>第3行</li>
  12. <li>第4行</li>
  13. <li>第5行</li>
  14. </ul>
  15. <script type="text/javascript">
  16. let lis = document.querySelector("#list")
  17. const list = document.querySelectorAll("#list li"); // 获取
  18. console.log(list);
  19. list.forEach((item, i) => { // 遍历
  20. item.style.background = "red"
  21. })
  22. document.body.style.background = "cadetblue"
  23. // 创建元素
  24. let newLi = document.createElement("li");
  25. newLi.textContent = "第6行";
  26. lis.insertAdjacentElement("beforeEnd", newLi);
  27. </script>
  28. <!-- 获取表单元素 -->
  29. <form action="" name="login" id="mylogin">
  30. <input type="text" name="text" value="hahahah">
  31. <button>提交</button>
  32. </form>
  33. <script type="text/javascript">
  34. console.log(document.forms.login.text.value); // 获取表单元素
  35. </script>
  36. </body>
  37. </html>