2016-01-16 42 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

哪個按鈕?我可以看到鏈接標記''。 –