2016-01-16 46 views
2

好家伙即时通讯建立一个库,比如我举一个属性附加伤害到html元素触发事件不会工作

<a href="https://google.com" shc="27"> 
logout 

像这样的SHC =“​​27”,这意味着当钥匙27(ESC )将被点击在键盘上,它会触发点击链接,但由于某种原因,它拒绝点击它。 这里是我的全码:

$(document).on("keydown", function(e) { 
    console.log(e.which); 
    checkElementType(e.which); 
}); 

function checkElementType(shortcutKey){ 
    var element = $("[shc="+shortcutKey+"]"); 
    var elementType = element.prop('nodeName'); 

    switch(elementType){ 
     case 'A': 

      console.log(element); 
      console.log('click the link'); 
      element.trigger('click'); 
     break; 
    } 
} 

这里是小提琴:Fiddle

+1

不相关的问题,但你应该使用['数据 - *'](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/data- *)属性而不是自定义属性。 – Andreas

+0

[jQuery的如何触发href元素上的点击事件]的可能重复(http://stackoverflow.com/questions/7999806/jquery-how-to-trigger-click-event-on-href-element) – Andreas

+0

@Andreas为什么使用数据属性而不是自定义属性? – Jazz

回答

1

变化element.trigger('click');element[0].click()

0

我甚至不知道我的变化,但它的工作原理

<html> 
<body> 
<a href="http://google.com" class="shortcut" shc="27"> 
    logout 
    </a> 
</body> 
</html> 

$(document).on("keydown", function(e) { 
    console.log(e.which); 
    checkElementType(e.which); 
}); 

function checkElementType(shortcutKey){ 
    var element = $("[shc="+shortcutKey+"]"); 
    var elementType = element.prop('nodeName'); 

    switch(elementType){ 
     case 'A': 
      element.trigger('click'); 
      console.log(element); 
      console.log('click the link'); 
     break; 
    } 
} 

https://jsfiddle.net/s8fk88ou/3/

0

你可以使用window.location.href属性打开链接基于href元素的属性:

window.location.href = element.attr('href'); 

希望这会有所帮助。


$(document).on("keydown", function(e) { 
 
\t \t console.log(e.which); 
 
\t \t checkElementType(e.which); 
 
\t }); 
 

 
\t function checkElementType(shortcutKey){ 
 
\t \t var element = $("[shc="+shortcutKey+"]"); 
 
\t \t var elementType = element.prop('nodeName'); 
 

 
\t \t switch(elementType){ 
 
\t \t \t case 'A': 
 
\t \t \t \t console.log(element); 
 
\t \t \t \t console.log('click the link'); 
 
       
 
       window.location.href = element.attr('href'); 
 
       //Or 
 
       //element[0].click(); 
 
       //Or 
 
       //element[0].trigger('click'); 
 
       
 
\t \t \t break; 
 
\t \t } 
 
\t }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<a href="http://google.com" class="shortcut" shc="27">logout</a>

+0

这工作,但有另一个问题,当我尝试触发一个按钮,它不会工作 – Jazz

+0

哪个按钮?我可以看到链接标记''。 –