来自js文件的我的函数没有从html文件调用

时间:2016-10-24 13:23:59

标签: javascript html css node.js html5

我正在使用节点js的网站上工作。我在js文件中添加了一个函数。现在,当我尝试从html页面调用该函数时,函数不会被调用。 这是我在html页面中使用的代码:

<div id ="bubble" class="bubble-style" data-action="getSpeechBubble()</div>

我刚刚在函数中添加了一个控制台语句:

getSpeechBubble: function() {

        console.log(' getSpeechBubble ');
}

1 个答案:

答案 0 :(得分:0)

创建和调用函数有几种方法,最常用的是

function getSpeechBubble(){
console.log("getSpeechBubble");
}
//get function from data-action attribute
var exc = document.getElementById("bubble").getAttribute("data-action");

//or window.addEventListener("load",new Function(exc),false);
window.onload = new Function(exc);
//or .addEventListener("clik",new Function(exc),false);
document.getElementById("bubble").onclick = new Function(exc);
<div id ="bubble" class="bubble-style" data-action="getSpeechBubble()">
click me
</div>

//1st way
this.getSpeechBubble = function() {
            console.log(' 1st way: getSpeechBubble ');
}
this.getSpeechBubble();
//2nd way
this["getSpeechBubble"] = function() {
            console.log(' 2nd way: getSpeechBubble ');
}
this["getSpeechBubble"]();
//3rd way
window["getSpeechBubble"] = function() {
            console.log(' 3rd way: getSpeechBubble ');
}
window["getSpeechBubble"]()
//4th way
var getSpeechBubble = function() {
            console.log(' 4th way: getSpeechBubble ');
}
getSpeechBubble();
//5th way
var js = {
getSpeechBubble: function(){
            console.log(' 5th way: getSpeechBubble ');
}
};
js.getSpeechBubble();
//6th way
function getSpeechBubble () {
            console.log(' 6th way: getSpeechBubble ');
}
getSpeechBubble();