简体   繁体   English

append 带有动态值的 jQuery 中 div 的 href 标记

[英]append a href tag to div in jQuery with dynamic values

var customlink= "<div style='text-align:left;'>some text is here";

customlink+="<a href='#' title='test link' class='class1' onclick='show('"+val1+"','"+val2+"','"+val3+"')';></a></div>"

When using the above code to create the hyperlink with dynamic value then hyperlink not created with dynamic values in single quotes.使用上述代码创建具有动态值的超链接时,未使用单引号中的动态值创建超链接。 it give me the below result.它给了我以下结果。

<a href="#" title="test link" class="class1" onclick="show(" 4','4','4')';=""></a>

what should I need to change in the above code?我应该在上面的代码中改变什么?

The issue is due to the use of quotes within the arguments of the method call.该问题是由于在方法调用的 arguments 中使用了引号引起的。 You need to escape them using the \ character:您需要使用\字符转义它们:

 var val1 = 1; var val2 = 2; var val3 = 3; var customlink = '<div style="text-align:left;">some text is here <a href="#" title="test link" class="class1" onclick="show(\'' + val1 + '\',\'' + val2 + '\',\'' + val3 + '\')";>Link...</a></div>'; document.querySelector('div').innerHTML = customlink; function show(a, b, c) { console.log(a, b, c); }
 <div></div>

Better yet avoid the problem entirely and improve the code quality by using data attributes along with an unobtrusive event handler:通过使用data属性和不显眼的事件处理程序,更好地完全避免该问题并提高代码质量:

 let val1 = 1; let val2 = 2; let val3 = 3; let customlink = `<div style="text-align: left;">some text is here <a href="#" title="test link" class="class1" data-val1="${val1}" data-val2="${val2}" data-val3="${val3}">Link...</a></div>`; let div = document.querySelector('div'); div.innerHTML = customlink; div.querySelector('a').addEventListener('click', e => { var elData = e.target.dataset; console.log(elData.val1); console.log(elData.val2); console.log(elData.val3); });
 <div></div>

I think you can do like this.我认为你可以这样做。

 function generatetage(val1,val2,val3){ var customlink= "<div style='text-align:left;'>some text is here"; customlink+=`<a href='#' title='test link' class='class1' onclick="show('${val1}','${val2}','${val3}')">testlink</a></div>` document.getElementById("tagarea").innerHTML=customlink; }
 <div id="tagarea"></div> <button onclick="generatetage(4,4,4)">testButton</button>

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

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