繁体   English   中英

如何使用内联 onclick 将 pug mixin 的 id 放入 javascript function

[英]How to get id of pug mixin into a javascript function with inline onclick

我正在尝试制作一个可以使用不同元素ID添加多个计数器的mixin。 我已经尝试了很多事情,我得到的最接近的工作示例就是这个。


mixin counter(count, id)
  h2(id=id)= count
  button(onclick="addId(1, this.textContent)")= id
  button(onclick ="addId(-1, this.textContent)")= id
  script.
    function addId(x,y){
      let element = document.getElementById(y);
      let content = element.textContent;
      element.textContent = Number(content) + x;
    }

然后我使用添加mixins

+counter(0, 'idToAdd')

这可行,但问题是按钮值必须是传入的 id 值。我希望一个按钮是添加,另一个是减去。 但是我尝试过的一切都失败了。 只有通过使用

this.textContent 

在按钮上我可以传递 id 然后它就可以工作了。 所以我想要做的是将显示元素的 id 传递到内联 onclick 而不使用 this.textContent 以便我可以适当地命名按钮。

我努力了

#{id}

!{id}

乃至

`${id}`

但似乎没有任何效果。

请帮忙。

谢谢

与其为每个计数器创建一个新的 function,不如创建一个适用于所有计数器的单个 function。 您可以使用模板字符串插值在onclick属性中直接将特定 ID 设置为 function 调用的参数:

mixin counter(count, id)
  h2(id= id) #{count}
  button(onclick=`updateCounter(1, '${id}')`) Add 1
  button(onclick=`updateCounter(-1, '${id}')`) Subtract 1

+counter(0, 'foo')
+counter(0, 'bar')

script.
  function updateCounter(by, id) {
    let element = document.getElementById(id);
    let currentCount = parseInt(element.textContent, 10);
    element.textContent = currentCount + by;
  }

编译为:

 <h2 id="foo">0</h2> <button onclick="updateCounter(1, 'foo')">Add 1</button> <button onclick="updateCounter(-1, 'foo')">Subtract 1</button> <h2 id="bar">0</h2> <button onclick="updateCounter(1, 'bar')">Add 1</button> <button onclick="updateCounter(-1, 'bar')">Subtract 1</button> <script> function updateCounter(by, id) { let element = document.getElementById(id); let currentCount = parseInt(element.textContent, 10); element.textContent = currentCount + by; } </script>

暂无
暂无

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

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