问题描述
以下代码不起作用
public void playSong(View v) {
this.songIntent = new Intent(Main4Activity.this,BackgroundSoundService.class);
this.songIntent.putExtra("song","su@R_502_6460@_" + randomresult);
final Button myButton = (Button) findViewById(R.id.button111);
myButton.setonClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
myButton.setVisibility(View.GONE);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(SHARED_KEY_BUTTON_HIDE,true);
editor.apply();
}
});
startService(this.songIntent);
}
<body>
<div id="demo"></div>
<input type="button" value="Click Here" onclick='()=>{document.getElementById("demo").innerText = "Hello World";}'>
<script type="text/javascript"></script>
</body>
我在这里做错什么了?
解决方法
内部事件属性值表示函数的主体。
您的代码等同于:
import React,{ Component } from "react";
class App extends Component {
constructor() {
super()
this.state = {
name: "test",age: 30
}
}
render() {
return (
<div>
<h1>{this.state.name} </h1>
<h3>{this.state.age} years old </h3>
</div>
);
};
}
export default App;
您已经定义了一个函数,该函数在被调用时(由点击事件触发)定义,但不会调用它或将其分配到任何地方。
与任何函数一样,您可以在函数主体中放入任何您喜欢的语句。它们不必是函数调用。
function onclick() {
()=>{document.getElementById("demo").innerText = "Hello World";}
}
请注意,内在事件属性被认为是不好的做法(它们无法分开关注点,它们具有令人惊讶的范围含义,这可能导致变量名冲突,并且它们很快会导致嵌套的引号字符地狱)。请改用the addEventListener
method。