如何通过使用javascript单击HTML上的按钮来发生事件

时间:2017-04-14 01:20:53

标签: javascript html button onclick

我正在尝试将HTML打印出来"德国"当您单击按钮时。但它无法正常工作。我的代码中有什么问题吗?

HTML

<input type="button" value="click!" onclick="shuffle();"/>
<div id="output"></div>

的Javascript

(function(){
    window.onload = function(){
        alert("welcome to my trip record");
    }
})();

var shuffle = function(){
    var target = document.getElementById("output");
    target.innerHTML = "Germany";
}

4 个答案:

答案 0 :(得分:1)

;

中删除onclick
<input type="button" value="click!" onclick="shuffle()"/>

答案 1 :(得分:1)

尝试在按钮单击

上使用addEventListener for make event
document.getElementById("myBtn").addEventListener("click", function(){
    var target = document.getElementById("output");
    target.innerHTML = "Germany";
});

这是工作的jsfiddle:https://jsfiddle.net/jxjpzvvz/

答案 2 :(得分:0)

const sprintf = require("sprintf-js").sprintf;

var o_substit = {
  path1 : "mypath1"
};

var T_URL = "/someurl/%(path1)s/%(path2)s/";


console.log(`\nT_URL:${T_URL}, substitutions:`);
try {
  console.dir(o_substit);
  console.log("expecting a failure...")
  var url = sprintf(T_URL, o_substit);
  console.log(`  url:${url}:`);
}
catch (e){
  console.log(`  exception:${e}`);  
};

var o_substit = {
  path1 : "mypath1"
  ,path2 : "mypath2"
};


console.log(`\nT_URL:${T_URL}, substitutions:`);
try{
  console.dir(o_substit);
  console.log("\nexpecting a success:")
  var url = sprintf(T_URL, o_substit);
  console.log(`  url:${url}:`);
}
catch (e){
  console.log(`  exception:${e}`);  
};

使用按钮元素作为按钮,而不是输入类型按钮。我们不是在html 4.0的时候;)

T_URL:/someurl/%(path1)s/%(path2)s/, substitutions:
{ path1: 'mypath1' }
expecting a failure...
  exception:Error: [sprintf] property 'path2' does not exist

T_URL:/someurl/%(path1)s/%(path2)s/, substitutions:
{ path1: 'mypath1', path2: 'mypath2' }

expecting a success:
  url:/someurl/mypath1/mypath2/:

我直接在html标签中没有js的粉丝,所以我为元素添加了一个监听器

答案 3 :(得分:0)

你犯了两个错误第一个错误<input />这没什么。第二个最常见的&#34; function();&#34;,&#34 ;;&#34;是错的

您的更正代码

&#13;
&#13;
(function(){
    window.onload = function(){
        alert("welcome to my trip record");
    }
})();

var shuffle = function(){
    var target = document.getElementById("output");
    target.innerHTML = "Germany";
}
&#13;
<input type="button" value="click!" onclick="shuffle()"/>
<div id="output"></div>
&#13;
&#13;
&#13;

我喜欢使用DOM EventListener

&#13;
&#13;
window.onload = function(){
    alert("welcome to my trip record");
}
document.getElementById("myBtn").addEventListener("click", function_t);
function function_t(){
var target = document.getElementById("output");
target.innerHTML = "Germany";
}
&#13;
 <input type="button" value="click!" id = "myBtn" >
 <div id="output"></div>
&#13;
&#13;
&#13;