簡體   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