将参数传递给通过“onclick”属性调用的 javascript 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6456213/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:44:28  来源:igfitidea点击:

Passing parameters to a javascript function called through 'onclick' attribute

javascriptjsf

提问by Rajat Gupta

I need to create links on webpage which call a javascript function with different parameters on being triggered by onclickevent. Thus function needs to be passed a paramter.

我需要在网页上创建链接,在被onclick事件触发时调用具有不同参数的 javascript 函数。因此函数需要传递一个参数。

In my code as shown below, I am passing a parameter to wr()function when calling from onclickwithin commandLink. Howver the code doesnt successfully execute if I pass ias parameter to wr()function within onclick, but is successful if I pass a constant ie, wr(4). How can I successfully pass a variable parameter to this javascript function ?

在我的代码中,如下所示,我在wr()onclick内部调用时将参数传递给函数commandLink。Howver代码犯规成功执行,如果我传递i的参数wr()内的功能onclick,但是是成功的,如果我通过一个常数即wr(4)。我怎样才能成功地将一个可变参数传递给这个 javascript 函数?

            <h:form>
                <ui:repeat value="#{bean.list}" var="i">
                    <p:commandLink onclick="wr(i)" value="#{i}" /><br/>
                </ui:repeat>
            </h:form>

            <p id="e">fd</p>

            <script type="text/javascript" >
                function wr(i){
                    document.getElementById("e").innerHTML="this is "+i+ " !";
                }
            </script>

采纳答案by toddk

Shouldn't your markup for the onclick attribute evaluate the variable 'i' using #{i} instead of just passing 'i'?

您的 onclick 属性标记不应该使用 #{i} 而不是仅传递 'i' 来评估变量 'i' 吗?

So it should be:

所以应该是:

<ui:repeat value="#{bean.list}" var="i">
  <p:commandLink onclick="wr(#{i})" value="'#{i}'" /><br/>
</ui:repeat>

Have you used something like FireBugto see what 'i' is evaluting too inside of your JS function?

您是否使用过FireBug 之类的东西来查看 'i' 在您的 JS 函数内部正在评估什么?

Edit:Updated the markup above to enclose the #{i} expression in single '' quotes

编辑:更新了上面的标记以将 #{i} 表达式括在单 '' 引号中

回答by Armaan Dhir

You should do this:

你应该做这个:

<ui:repeat value="#{bean.list}" var="i">
   <p:commandLink onclick="wr('#{i}')" /><br/>
</ui:repeat>

回答by Mic

You should pass the reference of the element using this. It is more flexible than just passing hard parameters.

您应该使用this. 它比仅仅传递硬参数更灵活。

eg: ...onclick="wr(this)"...

例如: ...onclick="wr(this)"...

and then

接着

function wr(elm){
  document.getElementById("e").innerHTML="this is "+ elm.value + " !";
}