簡體   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