繁体   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