开发者

Automatically activate the anchored tab

I'm experimenting with some JavaScript code and run into a problem where an element tells me can't be clicked. The goal is to activate a tab based on the anchor in the URL. Here's the short version:

<tab onClick="showTab('Dogs')">Dogs</tab>
<tab onClick="showTab('Cats')">Cats</tab>
<script type="text/javascript">
var chunks = document.URL.split('#')
if(chunks.length > 1) {
  var anchored_tab = chunks.pop().toLowerCase()
  var tabs = document.getElementsByTagName('tab')
  for(i in tabs) {
    if(tabs[i].innerHTML.toLowerCase() == anchored_tab) {
      alert("trying to click tab "+tabs[i].innerHTML)
      tabs[i].click()  // TypeError: Object#<HTMLElement> has no method 'click'
    }
  }
}
</script>

Assuming the开发者_运维知识库 URL ends with "#dogs", the alert correctly says "trying to click tab Dogs", but then I get an exception on the next line saying the element doesn't have a click method.

I'm testing on Chrome 12.


You can add the following code somewhere above what you have now, which will add a trigger event to the actual click event in browsers that don't let you click() directly. Please note that this type of functionality is often wrapped up in a library such as jquery or prototype.

if(typeof HTMLElement!='undefined'&&!HTMLElement.prototype.click) {
    HTMLElement.prototype.click=function() {
        var evt = this.ownerDocument.createEvent('MouseEvents');
        evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
        this.dispatchEvent(evt);
    }
}


not all browsers support click() on html elements. you can try .onclick() but your best bet would be to use a cross browser supported click event trigger like in jQuery or another js library

checkout this old post for more info

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜