簡體   English   中英

如何將參數傳遞到onclick函數參數到動態創建的按鈕?

[英]How to pass parameters into onclick function parameters into dynamically created buttons?

我的javascript從文件中讀取文本,並根據下面的按鈕創建動態創建按鈕。 我面臨的問題是它無法在點擊時調用該功能。 我已經嘗試刪除參數來調用它,它可以工作,但我似乎無法讓它與傳遞參數一起工作。 有人可以幫我嗎?

JS:

function toggleVisibility(type){
    alert(type);
}

按鈕創建:

var button='<button type="button" class="btn btn-block btn-inverse active" data-toggle="button tooltip" title="Click this to enable/disable viewing of '+this+'" onclick="toggleVisibility('+"'"+this+"'"+')">'+word+'</button>';

首先,您不應該使用內聯處理程序,並且使用jQuery創建它更容易:

var that = this;
var button = $("<button>");
button.addClass("btn btn-block btn-inverse active");
button.attr({
    type: "button",
    "data-toggle": "button tooltip",
    title: "Click this to enable/disable viewing of " + that
});
button.text(word);
button.on("click", function () {
    toggleVisibility(that);
});

(是的,我知道你可以鏈接所有的方法調用,我只是想這樣做)

當你准備把這個按鈕放在某處時,只需使用$container.append(button);

一切都取決於this是什么或你想要/期望它是什么。 如果你需要傳遞給toggleVisibility的參數成為剛剛點擊的特定按鈕(我猜是要切換它的可見性),只需傳遞this (忽略that )。 至於設置title屬性,我不確定你想要什么:)

如果你有一個HTML結構,如:

<div id="container">
    <!-- Buttons go somewhere in here -->
</div>

並且您將按鈕附加到該容器(或該容器中的某個位置),使用事件委派將單個click處理程序綁定到容器會更有效:

$("#container").on("click", ".special-btn-identifier", function () {
    toggleVisibility(this);
});

當然,您需要在按鈕中添加“special-btn-identifier”類,以便此事件處理程序可以工作(並刪除每個按鈕的各個click處理程序,因為這將覆蓋它們)。 這個單一事件處理程序只需要運行一次,最好只要#container就緒就好......就像$(document).ready(function () {});

替換以下行:

.. onclick="toggleVisibility('+"'"+this+"'"+')">'+word+'</button>';

對於這一個:

.. onclick="toggleVisibility(this)">'+word+'</button>';

因為你不需要逃避this關鍵字,也包括不同this從那里你正在創建按鈕文本上下文。

在創建按鈕時,在文檔上而不是在html中注冊onClick事件。

$(document).on('click', 'button.btn-inverse', function() { toggleVisibility(this); return false;});

不要創建內聯HTML字符串,不要使用侵入式Javascript。

雖然我甚至不建議您使用vanilla jQuery創建它們,但您可以嘗試:

var $button = $('<button></button>', {
  'text'        : word
  'type'        : 'button',
  'class'       : 'btn btn-block btn-inverse active',
  'data-toggle' : 'button tooltip',
  ...
  // any other attributes
});

// append the $button anywere

$( someContainer ).append($button);

$( someContainer ).on('click', '.btn', function(event){

  // you can refer to the button with $(this) here

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM