【问题标题】:Passing element ID to function将元素 ID 传递给函数
【发布时间】:2014-05-07 22:23:43
【问题描述】:

我有这个功能:

function op_up(){
    this.style.color=#FF0000;
}

我有这个 HTML 元素:

<span id="trigger" onClick="op_up(#element_1)">Click to change #element_1<span>
<span id="trigger" onClick="op_up(#element_2)">Click to change #element_2<span>

我希望该函数影响 onClick 事件中元素的 id。

任何帮助将不胜感激。谢谢:)

【问题讨论】:

  • ID 在 JS 中是字符串,如何将它们传递给函数并没有什么特别之处。你的问题是什么?也许您正在寻找document.getElementById(op_id)?或者other_id 是一个隐含的全局变量,包含具有该 ID 的元素?然后只需在函数内使用op_id 而不是this。 FWIW,this 无论如何也不起作用。
  • +1 @FelixKling 提到的内容。除了 OP 可能想使用document.getElementById(other_id)
  • 我正在尝试将 ID other_id 从 onClick 事件传递给函数。
  • @AlfredPersonMc:看来你已经在这样做了,op_up(other_id)。也许您必须改为传递一个字符串op_up('other_id'),但是从您提供的小解释中确实不清楚。如果你提供一个完整的例子,你可能会得到更好的帮助。见stackoverflow.com/help/mcve
  • 好的,我会重新提出问题...

标签: javascript function parameter-passing


【解决方案1】:

您的函数调用无效,但您可以将 字符串 传递给函数:

op_up('#element_1')

然后你可以使用document.querySelector 来获取对元素的引用:

function op_up(selector){
    document.querySelector(selector).style.color='#FF0000';
}

或者正如我在 cmets 中已经说过的,如果您将 ID 传递为

op_up('element_1')

使用document.getElementById:

function op_up(id){
    document.getElementById(id).style.color='#FF0000';
}

【讨论】:

  • 因为您没有正确设置小提琴,并且颜色也必须在字符串中。复制粘贴你的错误:P 见stackoverflow.com/q/17512582/218196
  • 正如我所说,要么您没有将颜色放入字符串中,要么您没有更改 jsfiddle 以将函数放入头部或正文中。见:jsfiddle.net/p9rp6/1
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-15
  • 2017-02-13
  • 2020-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多