【问题标题】:how to get id of event.target from javascript function?如何从 javascript 函数中获取 event.target 的 id?
【发布时间】:2018-04-19 02:39:29
【问题描述】:

例如:

function helloworld(){
    alert("helloworld");
}

function worldhello(){
    alert("worldhello");
}

两个功能和三个按钮。

点击'A'按钮将执行helloworld()函数。

点击'B'按钮将执行worldhello()函数。

当你点击'C'按钮时,helloworld ()函数被执行,worldhello ()函数被执行。

我想防止在单击'C'按钮时执行helloworld()函数的警报。

我尝试使用event.target.id$(event.target).attr("id")helloworld() 函数中找到'C' 按钮的id,但它打印了undefined

如何在helloworld ()函数中找到'C'按钮的id

【问题讨论】:

  • I tried to use 能否发布您尝试过的代码,以便我们尝试调试它?
  • @CertainPerformance 此代码是示例..

标签: javascript events target


【解决方案1】:

我不明白你在获得元素的 ID 后会做什么,无论如何,有更通用的方法可以做到这一点。您可以将标志传递给您的函数,以决定是否显示警报。

试试这个:

<button onclick="hw(true)">A</button>
<button onclick="wh(true)">B</button>
<button onclick="hw(false); wh(true)">C</button>

<script>
  let hw = shouldAlert => {
    if (shouldAlert) {
      alert("Hello World!");
    }
  };

  let wh = shouldAlert => {
    if (shouldAlert) {
      alert("World Hello!");
    }
  };
</script>

希望对你有帮助!

【讨论】:

  • 您应该避免使用内联处理程序 - 它与eval 基本相同,并且是非常糟糕的做法。而是使用 Javascript 附加侦听器。此外,当不打算重新分配变量时,应使用const 而不是let 声明它。 let 告诉读者您将重新分配有问题的变量。
  • @CertainPerformance 感谢您的提示。除了可读性,使用 const 代替 let 还有其他意义吗?
  • 不,但在编写可维护代码时,可读性通常是最重要的考虑因素,尤其是在大型应用程序中。出于同样的原因,您现在看到人们使用mapreducefilter 等等而不是使用for 循环,即使for 循环更快 - 因为数组方法更具可读性。
猜你喜欢
  • 2011-09-10
  • 2018-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-10
  • 2018-10-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多