2013-01-08 26 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函数。 –