我需要在一个名为redirect()的函数中传递一个JavaScript变量,当用户单击链接并且该链接是动态生成时将调用该变量。 这是我的代码;
$(document).ready(function (){
//this code will generate div when the page loads first time
var n = 9;
for(var i=0;i<n;i++){
var div = document.createElement('div');
div.className = "d5";
div.id=i+1;
// alert(div.id);
document.getElementById('container').appendChild(div);
$.ajax({
async: false,
url: 'myapi.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
var Name = data[2];
var subdomain=data[15];
var uniqueid=data[1];
var shop_photo=data[3];
var offer=data[19]; //get id
//var vname = data[1]; //get name
//$('#'+div.id).html("<a href='http://www."+subdomain+".xyz.com'>"+Name+"</a>");
//$('#'+div.id).html("<img class='shopperspic' src='b2b/shop_image/"+uniqueid+"/"+shop_photo+"' alt='' /><a href='http://www."+subdomain+".xyz.com'>"+Name+"</a><br>Special Offer<br><p>"+offer+"</p>");
if(offer=="")
{
$('#'+div.id).html("<div class='div1'><img class='shopperspic' src='b2b/shop_image/"+uniqueid+"/"+shop_photo+"' alt='' /></div><div class='div2'><a href='http://www."+subdomain+".xyz.com' onclick='redirect()'>"+Name+"</a></div></div>");
}
else
{
$('#'+div.id).html("<div class='div1'><img class='shopperspic' src='b2b/shop_image/"+uniqueid+"/"+shop_photo+"' alt='' /></div><div class='div2'><a href='http://www."+subdomain+".xyz.com' onclick='redirect()>"+Name+"</a></div><div class='div3'>Special Offer<br class='br_special'>"+offer+"</div></div>");
}
}
});
}//this code will generate div when the page loads first time
我需要在函数redirect()
中传递变量var subdomain
我的函数redirect()是这样的:
<script type="text/javascript">
function redirect(a)
{
alert(a);//just for showing the passed variable I am using this alert();
}
</script>
最佳答案
将 ID 添加到 anchor 标记,例如 <a id='id001' href='....'
然后做
document.getElementById("id001").addEventListener("click", function() {
重定向(子域名);});
关于javascript - 如何在动态生成链接的 onClick 事件的函数中传递 JavaScript 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28471262/