javascript html 输入 onchange 不接受匿名函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24069843/
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-28 02:07:39  来源:igfitidea点击:

html input onchange doesn't accept anonymous function

javascripthtmlmodel-view-controllerinput

提问by dooderson

Why does this not work?

为什么这不起作用?

 <input type="file" id="kmlFiles2" multiple onchange="function(){alert('why does this not work')}()">

chrome gives me an error, Uncaught SyntaxError: Unexpected token (.

chrome 给我一个错误, Uncaught SyntaxError: Unexpected token (.

Firefox tells me SyntaxError: function statement requires a name.

Firefox 告诉我SyntaxError: function statement requires a name

But this does work?

但这行得通吗?

 <input type="file" id="kmlFiles2" multiple onchange="alert('but this does work')">

http://jsfiddle.net/ewzyV/

http://jsfiddle.net/ewzyV/

I am asking because I was was trying to use and MVC framework that injects code into the onchange event.

我问是因为我试图使用 MVC 框架将代码注入 onchange 事件。

回答by aljgom

onchange="(function(){alert('this should work')})()"

回答by Karthik

Its not a good practice to create inline functions.

创建内联函数不是一个好习惯。

I would suggest something like

我会建议像

<html>
 <script>
   function myFunction(){
     alert('hey it works');
   }
 </script>
 <body>
 <input type ='file' id='kmlFiles2' onchange="myFunction();" />
 </body>
 </html>

you can also consider writing

你也可以考虑写

function init(){
   document.getElementById('kmlFiles2').onclick=function(){alert('this also works');};
}
window.onload=init;

回答by Stephen Elliott

                                                            ??''?

With your code segment:

使用您的代码段:

    onchange="function(){alert('why does this not work')}()"

there is a basic problem. I would expect from https://www.w3schools.com/jsref/event_onchange.aspthat the format for Javascript is (instead):

有一个基本问题。我希望https://www.w3schools.com/jsref/event_onchange.aspJavascript 的格式是(而不是):

    object.onchange = function(){myScript};

With the onchange evenet, the "object." is implicit already, so the expected correct form to use would be:

随着 onchange 事件,“对象”。已经是隐式的,所以预期使用的正确形式是:

    onchange= "function(){alert("Why does this not work?"); return;}"

The absence of the "return;" statement rarely gives problems but - even so - I include it to make the function complete.

没有“回报”;语句很少出现问题,但 - 即便如此 - 我将它包含在内以使功能完整。

I have a similar situation that I am trying to resolve, so I very much appreciate your bringing up the question. Thank you and good luck with your programming!

我有一个类似的情况,我正在努力解决,所以我非常感谢你提出这个问题。谢谢你,祝你编程好运!

I am starting with this reference:

我从这个参考开始:

https://www.w3schools.com/js/js_function_definition.asp

https://www.w3schools.com/js/js_function_definition.asp

    After a function expression has been stored in a variable, the 
    variable can be used as a function:
    Example
    var x = function (a, b) {return a * b};
    var z = x(4, 3); 

I found that the following code is working:

我发现以下代码有效:

    onchange="{alert('Hello 10'); alert('Hello 20'); return; }"

It seems that the "function()" is implicit also. I tested it and the alert posted two times. I started out with just the single alert. Since it works for me, you might want to give this as a hint how it "should" work hopefully for you too.

似乎“function()”也是隐含的。我测试了它并且警报发布了两次。我开始时只有一个警报。既然它对我有用,你可能想把它作为一个提示,它“应该”如何对你有用。

After testing awhile with the inline functions, they seemed to unstable in order to get something consistently working. So I ended up with the code below that works solidly for me, simply defining a function to do what needs to be done:

使用内联函数测试一段时间后,它们似乎不稳定,以便使某些东西始终如一地工作。所以我最终得到了下面的代码,这些代码对我来说很有效,只需定义一个函数来完成需要做的事情:

<td><strong>Number of Posts For the Carousel to Show:</strong></td>
<td style="text-align: center; vertical-align: middle; padding: 10px;" colspan="2">
<input id="<?php echo esc_attr( $this->get_field_id( 'ceupoststoshow' ) ); ?>" style="vertical-align: middle; horizontal-align: middle;" max="20" min="1" step="1" type="range" value="<?php echo esc_attr( $titleooi ); ?>" onchange="updatetwopoststoshowtext(this.value, this.id, 'ceupoststoshow' , 'titleooi','ceupoststoshowtext')" >
<script type="text/javascript">
function updatetwopoststoshowtext(thistextvalue, thisfieldid, thisoldfromid, thisnewtoidone, thisnewtoidtwo) {
updatepoststoshowtext(thistextvalue, thisfieldid, thisoldfromid , thisnewtoidone);
updatepoststoshowtext(thistextvalue, thisfieldid, thisoldfromid , thisnewtoidtwo);
}
</script>

</td>
<td>
<input style="width: 90%;" type="text" id="<?php echo esc_attr( $this->get_field_id( 'ceupoststoshowtext' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'ceupoststoshowtext') ); ?>" type="text" value="<?php echo esc_attr( $titleooi ); ?>" onchange="updatepoststoshowtext(this.value, this.id, 'ceupoststoshowtext' , 'titleooi')" >

<script type="text/javascript">
function updatepoststoshowtext(thistextvalue, thisfieldid, thisoldfromid, thisnewtoid) {
var strthistextvalue= String(thistextvalue); var strthisfieldid = String(thisfieldid); 
var strthisoldfromid=String(thisoldfromid); var strthisnewtoid = String(thisnewtoid);
alert ("UPST hello there! strthistextvalue = " + strthistextvalue + " strthisfieldid = " + strthisfieldid + " strthisoldfromid = " + strthisoldfromid + " strthisnewtoid = " + strthisnewtoid );

var subfieldidlength = strthisfieldid.length - strthisoldfromid.length;
var substrfieldid = strthisfieldid.substring (0, subfieldidlength);
alert ("UPST hello there two! subfieldidlength = " + subfieldidlength + " substrfieldid = " + substrfieldid);

var newstrfieldid = substrfieldid + strthisnewtoid;
alert ("UPST hello there three one! newstrfieldid = " + newstrfieldid);
var newElementId = document.getElementById(newstrfieldid);  
alert ("UPST hello there three two! newElementId.value = " + newElementId.value);
(document.getElementById(newstrfieldid)).value = strthistextvalue;
alert ("UPST hello there three! (document.getElementById(newstrfieldid)).value = " + strthistextvalue);

alert ("document.getElementById (newstrfieldid = " +  newstrfieldid + " ) . value = thistextvalue = " + thistextvalue);
return;
}
</script>

回答by Stephen Elliott

you can't call the anonymous function from html element so you can achieve this by event handling like:

您不能从 html 元素调用匿名函数,因此您可以通过如下事件处理来实现:

<input type="file" id="kmlFiles2" multiple>
 <script>
    document.getElementById("kmlFiles2").addEventListener("change", function(){
        alert('This is working')
    })
 </script>