Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
710 views
in Technique[技术] by (71.8m points)

internet explorer - Javascript click function

I've got some code which works fine in IE but unfortunately not in Google Chrome/Firefox.

It relies upon calling a click() event on a button from javascript. Reading around it seems that this is an IE specific extension (doh). Is there any way I can do a similar thing in chrome + firefox? To clarify, it's executing the click event on a specific button, not handling what happens when the user clicks on a button.

Thanks

The code for those who asked for it:

function getLinkButton(actionsDiv)
{
    var hrefs = actionsDiv.getElementsByTagName("a");
    for (var i=0; i<hrefs.length; i++)
    {
        var id = hrefs[i].id;
        if (id !=null && id.endsWith("ShowSimilarLinkButton"))
        {
            return hrefs[i];
        }
    }
    return null;
}

function doStuff()
{
  //find the specific actions div... not important code...
  var actionsDiv = getActionsDiv(); 
  var linkButton = getLinkButton(actionsDiv);

  if (linkButton != null)
  {
    if (linkButton.click)
    {
        linkButton.click();
    }
    else
    {
        alert("Cannot click");
    }
  }
}

I don't really want to use jQuery unless absolutely necessary

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you're looking for element.dispatchEvent:

function simulateClick() {
  var evt = document.createEvent("MouseEvents");
  evt.initMouseEvent("click", true, true, window,
    0, 0, 0, 0, 0, false, false, false, false, 0, null);
  var cb = document.getElementById("checkbox"); 
  var canceled = !cb.dispatchEvent(evt);
  if(canceled) {
    // A handler called preventDefault
    alert("canceled");
  } else {
    // None of the handlers called preventDefault
    alert("not canceled");
  }
}

I read your question as "I'm trying to fire the onclick event for my button", whereas everyone else seems to have read it as "I'm trying to handle an onclick event for my button". Please let me know if I've got this wrong.

Modifying your code, a proper x-browser implementation might be:

if (linkButton != null) 
{ 
  if (linkButton.fireEvent) 
    linkButton.fireEvent("onclick"); 
  else 
  { 
    var evt = document.createEvent("MouseEvents");
    evt.initMouseEvent("click", true, true, window,
                               0, 0, 0, 0, 0, false, false, false, false, 0, null);
    linkButton.dispatchEvent(evt);
  } 
} 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...