在模板文字中传递onclick事件

时间:2017-07-16 14:01:17

标签: javascript ecmascript-6

我试图通过onclick事件传递url,它无法正常工作。  一旦页面加载

,就会<body onload="displayBookmarks()">初始化displayBookmarks函数
function deleteBookmark(url){
    alert(url);
};

function displayBookmarks(){
    bookmarksResults.innerHTML = "";
    for (let a in bookmarks){
        let name = bookmarks[a].name;
        let url =  bookmarks[a].url;
        bookmarksResults.innerHTML += `<div class="well"> <h3> ${name} <a class="btn btn-default" target="_blank" href=${url} >Visit</a>  <a onclick=${deleteBookmark(url)} class="btn btn-danger" >Delete</a></h3></div>`
    }
}

主要问题是onclick=${deleteBookmark(url)} 一旦页面加载,它就会开始显示网址但我只想在按下删除按钮时显示。

2 个答案:

答案 0 :(得分:1)

&#13;
&#13;
const markUp = `
    <button onclick="myFunction()">Click me</button>
`;

document.body.innerHTML = markUp;

window.myFunction = () => {
    console.log('Button clicked');
};
&#13;
&#13;
&#13;

答案 1 :(得分:1)

我发现使用封装还有另一种方法可以做到这一点。我不知道我是否会建议这样做,但是因为你已经问了这个问题。

&#13;
&#13;
Operation was explicitly assigned to /device:gpu:0 but available devices are  
[ /job:localhost/replica:0/task:0/device:CPU:0 ]. 
Make sure the device specification refers to a valid device.
&#13;
const app = document.getElementById("app");

const button = ((app) => {
  
  let _url;
  
	const _log = (data) => {
  	console.log(data);
  }
  
  let _content = `<button onclick="(${_log})('${_url}')">test</button>`;
  
  const _setContent = () => {
  	_content = `<button onclick="(${_log})('${_url}')">test</button>`;
  }
  
  const _setUrl = (url) => {
  	_url = url;
  }
  
  return {
  	setUrl: (url) => {
    	_setUrl(url);
      _setContent();
    },
  	render: () => {
    	app.innerHTML = _content;
    }
  }
})(app)

const url =  'www.something.com';
button.setUrl(url);
button.render();
&#13;
&#13;
&#13;