繁体   English   中英

如何将参数传递给javascript onclick函数。请不要使用jquery

[英]How pass parameter to a javascript onclick function.No jquery please

我创建了一个按钮,然后单击它的onclick,我想将属性值传递给函数

<button type="button"  name="createTask" id="createTask" class="createButton" onclick="Components.init(this)" >Add Task</button>

我在外部js文件中也有一个javascript函数

var Components = function(attributes){
var attributed = attributes;
 var _init = function(){
    console.log("Method Executing:Compnents.init")
    alert(attributes.id)        

    }
return {
    init:_init,

    }
}()

但是警告此消息显示未定义。如何将参数传递给此javascript函数。 我已经包含了这个component.js,它在html主体的底部具有此功能

尝试这个:

 Components = { init: function(component) { console.log("Method Executing:Components.init"); alert(component.id); } }; 
 <button type="button" name="createTask" id="createTask" class="createButton" onclick="Components.init(this)" >Add Task</button> 

<script>

var Components = function(){

var attributes;

var _init = function(elm){
    attributes = elm.attributes;
    console.log("Method Executing:Compnents.init")
    console.log(attributes.id.value);        
}

return {
    init:_init,
}

}();

</script>

在您的代码中:

var Components = function(attributes){

按照约定,以大写字母开头的函数保留给构造函数使用。 将IIFE括在括号中是很体贴的,因此很明显,从一开始它就是IIFE。

变量属性包含在形式参数列表中,实际上与声明它相同。 没有参数传递给它,因此其值是undefined 因此,以下声明不执行任何操作。

  var attributed = attributes;

  var _init = function(){
    console.log("Method Executing:Compnents.init")
    alert(attributes.id)

由于属性是不确定的,因此尝试访问id属性将引发错误。

  }
  return {
    init:_init,
  }

后面有逗号(,),这是语法错误。 始终使用分号也是一个好主意。

}()

啊,最后是IIFE。

固定版本的代码:

var components = (function() {
  var _init = function(attributes) {
    console.log("Method Executing:Compnents.init");
    alert(attributes.id);      
  };
  return {
    init:_init
  };
}());

并且必须更改调用以反映新的函数名称:

<button id="createTask" onclick="components.init(this)" >Add Task</button>

如果要保留在闭包中传递的值,则需要另一个参数:

var components = (function() {
  var storedAttributes;

  var _init = function(attributes) {
    storedAttributes = attributes;
    console.log("Method Executing:Compnents.init");
    alert(attributes.id);      
  };

  var _foo = function() {
    //  Do stuff with attributes
  };

  return {
    init: _init,
    foo: _foo
  };
}());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM