如何在动态生成的链接的onClick事件的函数中传递JavaScript变量?

时间:2015-02-12 07:01:54

标签: javascript php jquery html ajax

我需要在名为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

我需要在函数var subdomain

中传递变量redirect()

我的函数redirect()是这样的:

<script type="text/javascript">
    function redirect(a)
    {
        alert(a);//just for showing the passed variable I am using this alert();
    }
    </script>

3 个答案:

答案 0 :(得分:0)

只需将其插入到具有正确类型
的函数调用中 对于字符串类型:

var html = "<a href='http://www."+subdomain+".xyz.com' onclick='redirect(\""+subdomain +"\")>"+Name+"</a>"

答案 1 :(得分:0)

为您的锚标记添加ID,例如<a id='id001' href='....' 然后做     document.getElementById(“id001”)。 addEventListener(“click”,function(){     重定向(亚结构域);});

答案 2 :(得分:0)

试试这个:

       $('#'+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("+ subdomain +")'>"+Name+"</a></div></div>");