如何避免JavaScript代码重复以响应HTML中的多个div。

huangapple go评论72阅读模式
英文:

How to avoid javascript code duplication to respond to multiple div in the html

问题

以下是翻译好的部分:

原始代码如下:

<!DOCTYPE html>
<html>
<body>

<h2>Code to shrink</h2>

<div class="myform1">
  <input class="button-primary" type="button" id="btn1" value="ON">
  <input class="button-primary" type="button" id="btn2" value="OFF">     
</div>
<div class="myform2">
  <input class="button-primary" type="button" id="btn3" value="ON">
  <input class="button-primary" type="button" id="btn4" value="OFF">     
</div>

<script>
const Form1 = document.querySelector('.myform1');
const Form2 = document.querySelector('.myform2');

if(Form1){

    Form1.addEventListener('click', (e)=>{
    
        e.preventDefault();

        alert(e.target.id);     

    })
}

if(Form2){

    Form2.addEventListener('click', (e)=>{
    
        e.preventDefault();

        alert(e.target.id);     

    })
}
</script>

</body>
</html>

你希望将两个div(myform1和myform2)保留在HTML代码中,但只使用一个JavaScript代码部分来处理这两个div的点击事件。你的想法如下:

<script>

...

//单个处理程序用于HTML中的两个或更多div
if(Form){

    Form.addEventListener('click', (e)=>{
    
        e.preventDefault();

        alert(e.target.id);     

    })
}

</script>

你想要如何实现这个任务呢?帮助将不胜感激,谢谢。

有助于实现精简JavaScript代码的线索或代码示例。

英文:

Current code as follows:

<!DOCTYPE html>
<html>
<body>

<h2>Code to shrink</h2>

<div class="myform1">
  <input class="button-primary" type="button" id="btn1" value="ON">
  <input class="button-primary" type="button" id="btn2" value="OFF">     
</div>
<div class="myform2">
  <input class="button-primary" type="button" id="btn3" value="ON">
  <input class="button-primary" type="button" id="btn4" value="OFF">     
</div>



<script>
const Form1 = document.querySelector('.myform1');
const Form2 = document.querySelector('.myform2');

if(Form1){

    Form1.addEventListener('click', (e)=>{
    
        e.preventDefault();

        alert(e.target.id);     

    })
}

if(Form2){

    Form2.addEventListener('click', (e)=>{
    
        e.preventDefault();

        alert(e.target.id);     

    })
}
</script>

</body>
</html>

There are 2 divs (myform1 and myform2) hence there are 2 javascript code portions (if(Form1) and if(Form2)) to handle each div as above.

My wish is to maintain the 2 divs as in the html code, yet only 1 javascript code portion to handle both divs event clicked ... I imagine that looks like below:

<script>

...

//single handler for both or more divs in the html
if(Form){

    Form.addEventListener('click', (e)=>{
    
        e.preventDefault();

        alert(e.target.id);     

    })
}

</script>

How do I achieve the task.
Help highly appreciated, thank you

Clue or code example to achieve shrink my javascript coding

答案1

得分: 2

你可以使用 querySelectorAll 将所有的HTML组件检索到一个列表中。在你的情况下,你可以在查询字符串中使用逗号运算符来使用多个选择器。

const forms = document.querySelectorAll('.myform1, .myform2');
forms.forEach(form => {
    form.addEventListener('click', (e) => {
        e.preventDefault();
        alert(e.target.id);
    })
})
英文:

You can use querySelectorAll to retrive all HTML components into a list. In your case, you can use the coma operator in the query string to use more more than 1 selector.

const forms = document.querySelectorAll('.myform1, .myform2');
forms.forEach(form => {
    form.addEventListener('click', (e)=>{

         e.preventDefault();

        alert(e.target.id);     

    })
})

答案2

得分: 0

你好,Shamsul!

这是一个棘手的问题!@Hola的解决方案可能正是你想要的。就我个人而言,我会再进一步。addEventListener 方法接受两个参数:事件名称和回调函数。这个回调函数不关心它附加到哪个组件,所以你可以将它分离出来并重用它,从而更清楚地知道哪些部分的代码被重新利用了。(这也有一些优点,如果你以后想要停止监听点击事件的话)。我想象中的代码可能是这样的...

document.querySelectorAll('.myform1, .myform2').forEach(form => {
    form.addEventListener('click', formClickHandler)
})

function formClickHandler(e) {
  e.preventDefault();
  alert(e.target.id);
}

我强烈建议查看 EventTarget.addEventListener 的文档。那里有很多信息!

希望这有所帮助!

英文:

Salutations, Shamsul!

This is a tricky one! @Hola's solution is probably exactly what you want. Personally, I would go one step further. The addEventListener method takes two arguments: an event name and a callback. This callback function doesn't care about what component it's attached to, so you can separate it out and reuse it, making it clearer exactly which parts of your code are being repurposed. (This has some advantages, too, if you ever want to stop listening for click events). I'm imagining something like so...

document.querySelectorAll('.myform1, .myform2').forEach(form => {
    form.addEventListener('click', formClickHandler)
})

function formClickHandler(e) {
  e.preventDefault();
  alert(e.target.id);
}

I totally recommend checking out the Docs on EventTarget.addEventListener, though. There's a lot, there!

Hope this helps!

huangapple
  • 本文由 发表于 2023年6月8日 23:06:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76433271.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定