2013-01-08 113 views
3

對不起,我的壞英文單詞。如何用JQuery觸發原始事件

您好,我在使用JQuery啓動自定義事件時遇到了一些問題。 我的問題是:

  • 我嘗試使用content_scripts API開發Google Chrome擴展。
  • 我的目標網站是發佈評論,如果我按enter鍵在textArea。
  • 我需要開發一個按鈕,如果點擊它,它會觸發相同的事件。

我試圖模擬使用http://jsfiddle.net/編輯這樣同樣的事情:

  $(document).ready(function(){ 
// this what the site do when press enter key on textarea , the submit form with ajax to publish a comment. 
      $("textarea").bind("keydown",function(e){ 
      if(e.which == 13){ 
       alert("enter pressed"); 
      } 
      }); 
    // this what i need to do, firing the same event when i click on my button which i added by my extension. 
      $("button").click(function(){ 
      var e = $.Event("keydown"); 
      e.which = 13; 
      $("textarea").trigger(e); 
      }); 
     }); 

上面的代碼是沒有任何問題,但運行時應用此模擬目標網站沒有動作發生。 我想象如果網站使用keydown,keyup或按鍵事件發佈評論,所以我嘗試使用所有事件類型,但我所有的嘗試失敗。 我能做些什麼來激發原始事件的相同效果,如實際按下回車鍵提交評論?

+0

我會創建一個應該在KeyDown事件處理程序和按鈕的Click中調用的方法。這很容易,看起來比手動觸發事件好得多.... – platon

+1

我認爲他的問題是他沒有實現原始事件處理程序方法,它是網頁的任何操作。他只是想提供一種觸發它的新方法。 – Barmar

+0

@Barmar,他的代碼包含$(「textarea」)。trigger();所以,問題在於觸發事件和相應的事件處理程序。因此,我的解決方案應該符合理想... – platon

回答

1

你可以只創建一個新的功能來提交您的意見,並調用它的時候:

  • 用戶按在文本區域ENTER
  • 用戶點擊按鈕

    $(document).ready(function(){ 
    
        function submitComment() 
        { 
         //Do what you want to submit the textarea text 
         var comment = $("textarea").html(); 
        } 
    
        $("textarea").bind("keydown",function(e){ 
         if(e.which == 13){ 
          submitComment(); 
         } 
        }); 
    
        $("button").click(function(){ 
         submitComment(); 
        }); 
    }); 
    
+0

你是對的,謝謝 – sdespont

+0

不,我不能從我的擴展站點調用JavaScript函數。 –

0

爲什麼不嘗試分離你的邏輯?這不是測試代碼,所以你可能需要使用它,但這種一般風格將工作,並完成似乎你想要做的事情。

function myFunction() 
{ 

    alert("enter pressed"); 
} 

$(document).ready(function(){ 
// this what the site do when press enter key on textarea , the submit form with ajax to publish a comment. 
      $("textarea").bind("keydown",function(e){ 
      if(eventArg.which == 13){ 
        myFunction(); 

       } 
      }); 


    // this what i need to do, firing the same event when i click on my button which i added by my extension. 
$("button").click(function(){ 
     myFunction(); 
    }); 
}); 
+0

不,我不能從我的擴展中的站點調用JavaScript函數。 –