簡體   English   中英

通過 javascript/jquery 添加一個帶有 onclick 功能的按鈕

[英]Adding a button, with onclick function, via javascript/jquery

我正在努力尋找通過附加了函數的 javascript/jquery 添加按鈕的正確語法。

現在我正在嘗試:

list.append("<button onclick='getFeed('http://open.live.bbc.co.uk/weather/feeds/en/PA2/3dayforecast.rss, showFeedResults')'>ButtonTest</button>");

但它返回:

<button onclick="getFeed(" http:="" open.live.bbc.co.uk="" weather="" feeds="" en="" pa2="" 3dayforecast.rss,="" showfeedresults')'="">ButtonTest</button>

本質上,我希望能夠創建

<button onclick="getFeed('http://open.live.bbc.co.uk/weather/feeds/en/B1/3dayforecast.rss', showFeedResults)" class="ui-btn-hidden">

在javascript中,但不知道如何......`

而且我似乎在創建同時使用單引號和雙引號的 html 元素時遇到了麻煩。

任何建議將不勝感激。

附加一個分配了單擊事件偵聽器的按鈕

使用純 JavaScript

 const NewEL = (tag, prop) => Object.assign(document.createElement(tag), prop); // Use like: const EL_btn = NewEL("button", { textContent: "Test button", onclick() { console.log(this); /* getFeed etc... */ }, }); document.body.append(EL_btn);

或者使用jQuery

http://api.jquery.com/on/

list.append("<button>ButtonTest</button>");

list.on("click", "button", function(){
    getFeed('http://open.live.bbc.co.uk/weather/feeds/en/PA2/3dayforecast.rss, showFeedResults');
});

對於動態生成的元素,使用.on()方法。

雖然我認為在整個列表上使用on處理程序更好,但在將事件添加到 DOM 之前將事件綁定到斷開連接的 DOM 元素也是完全可以接受的:

button = $("<button>Button Test</button>");

button.click(function () {
  getFeed('http://open.live.bbc.co.uk/weather/feeds/en/PA2/3dayforecast.rss, showFeedResults');
});

list.append(button);

在vanilla javascript中是這樣的

<div id="something"></div>

var something = document.getElementById("something");
var button = document.createElement("button");

function doSomething() {
    alert("hi");
}

button.id = "myButton";
button.textContent = "Click me";
button.addEventListener("click", doSomething, false);

something.appendChild(button);

jsfiddle 上

另外,內聯javascript:
<button onclick="getFeed()">
被認為是不好的做法,可能會導致許多意外問題。

首先使用 DOM API 創建元素:

var button = document.createElement('button');

接下來,設置其屬性:

button.addEventListener('click', function (e) {...});
button.appendChild(document.createTextNode('Button Test'));

最后,將其添加到文檔中:

someParentElement.appendChild(button);

暫無
暫無

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

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