繁体   English   中英

单击href时,使用参数调用JavaScript函数

[英]Call a JavaScript function with parameters when click on href

我正在尝试拿出代码,该代码将使用具有参数的JavaScript函数来创建href标签。 参数是一个字符串和一个转换为json字符串的对象。 我的尝试是这样的:

return '<a style="text-decoration:underline;cursor:pointer" target="_blank"' +
                   ' href="javascript:goToStateNewWindow(\'trending\', \'' + JSON.stringify(params) + '\')">' + value + '</a>';

错误是:

未捕获的SyntaxError:无效或意外的令牌

在“检查”窗口中,它看起来像这样:

<a style="text-decoration:underline;cursor:pointer" target="_blank" href="javascript:goToStateNewWindow('trending', '{" projectid":2313,"alarmsonly":"true"}')"="">test</a>

有人可以解释我做错了吗?

有人可以解释我做错了吗?

抱歉。 但是一切。 这是您应该如何在例如函数中创建元素的方法。

var a = document.createElement('a');
var t = document.createTextNode(value);
a.appendChild(t);
a.style.textDecoration = 'underline';
a.style.cursor = 'pointer';
a.setAttribute("target", "_blank");
document.body.appendChild(a); // or any other element you want the a to appear in
a.addEventListener("click", function(e) {
  e.preventDefault();
  goToStateNewWindow('trending', params);
});

请注意,您还可以在元素之前使用CSS设置样式。

首先,它不应该是<a>元素,而应该是<button> 如果需要,可以使用CSS使它看起来像<a>

其次,您应该使用document.createElement()创建en元素,添加属性并使用addEventListener()方法指定单击事件侦听器。

const element = document.createElement('button')
element.setAttribute('type', 'button')
element.setAttribute('style', 'text-decoration:underline;cursor:pointer;')
element.setAttribute('target', '_blank')
element.addEventListener('click', event => goToStateNewWindow('trending', params))
element.innerHTML = value

return element.outerHTML

我想解释一下为什么它不起作用。 这是因为在您的html中,您有href="javascript:...当您调用JSON.stringify(params)它返回{"projectid":2313,"alarmsonly":true}然后javascript解析器会在之后的第一个双引号处停止href="{" )和其余的( projectid":2313,"alarmsonly":true}... )成为无效的javascript。

我做了一个函数,用双引号替换了双引号,并且有效。 如果对象具有带双引号的字符串值,则可能不起作用。

 function goToStateNewWindow(route, body){ console.log('Route: ', route); console.log('Params: ', body); } function doublequotetosingle(obj) { return JSON.stringify(obj).replace(/"/g, "'");; } function test(params, value) { return '<a style="text-decoration:underline;cursor:pointer" target="_blank"' + ' href="javascript:goToStateNewWindow(\\'trending\\',' + doublequotetosingle(params) + ')">' + value + '</a>'; } document.body.insertAdjacentHTML('beforeend', test({ projectid: 2313, alarmsonly: true }, 'test')); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM