如何从JavaScript代码访问id并将其传递给其他函数

时间:2017-07-06 05:50:26

标签: javascript php

这是我的JavaScript代码,我想从此代码访问id并传递给函数

function register_popup(id,name,msg)
{                
    for(var iii = 0; iii < popups.length; iii++)
    {   
        //already registered. Bring it to front.
        if(id == popups[iii])
        {
            Array.remove(popups, iii);                   
            popups.unshift(id);
            calculate_popups();
            return;
        }
    }               
    var element = '<div class="msg_box" style="right:290px" id="'+ id +'">';
        element = element + '<div class="msg_head">'+ id +'';
        element = element + '<div class="close"><a href="javascript:close_popup(\''+ id +'\');">&#10005;</a></div></div>';
        element = element + '<div class="id"><a href="javascript:getchat(\''+ id +'\');"></a></div>';
        element = element +'<div class="msg_wrap"><div class="msg_body" class="msg-wgt-body" ><ul id="chatlog"></ul>'+ msg+'<div class="msg_push" id="textmesage">dg</div></div><div class="msg_footer" ><textarea id="myTextArea" class="msg_input"  rows="4" onkeypress="PushMessage(event , this);"+"\n">  </textarea></div></div>';

    document.getElementsByTagName("body")[0].innerHTML = document.getElementsByTagName("body")[0].innerHTML + element;  
    popups.unshift(id);      
    calculate_popups();
}

我想从这个函数中获取id添加传递给这个函数我是JavaScript的新手,请帮我解决这个问题。 这是我的功能

function getchat(id)
{
    alert("function reached to the getchat");
}

1 个答案:

答案 0 :(得分:0)

要从html执行功能,您可以使用onclick而不是href

function register_popup(id,name,msg)
{                
  for(var iii = 0; iii < popups.length; iii++)
   {   
     //already registered. Bring it to front.
     if(id == popups[iii])
       {
         Array.remove(popups, iii);
         popups.unshift(id);
         calculate_popups();
         return;
        }
   }               
    var element = '<div class="msg_box" style="right:290px" id="'+ id +'">';
        element = element + '<div class="msg_head">'+ id +'';
        element = element + '<div class="close"><a onclick="close_popup(\''+ id +'\');">&#10005;</a></div></div>';
         element = element + '<div class="id"><a onclick="getchat(\''+ id +'\');"></a></div>';
        element = element +'<div class="msg_wrap"><div class="msg_body" class="msg-wgt-body" ><ul id="chatlog"></ul>'+ msg+'<div class="msg_push" id="textmesage">dg</div></div><div class="msg_footer" ><textarea id="myTextArea" class="msg_input"  rows="4" onkeypress="PushMessage(event , this);"+"\n">  </textarea></div></div>';

    document.getElementsByTagName("body")[0].innerHTML = document.getElementsByTagName("body")[0].innerHTML + element;  
    popups.unshift(id);      
    calculate_popups();
}