如何将此Javascript代码转换为Jquery

时间:2013-01-11 12:00:55

标签: javascript jquery html

我有一个javascript代码:

javascript: function iptxt() {
    var d = document;
    try {
        if (!d.body) throw (0);
        window.location = 'http://www.instapaper.com/text?u=' + encodeURIComponent(d.location.href);
    } catch (e) {
        alert('Please wait until the page has loaded.');
    }
}
iptxt();
void(0)

我会像这样使用它:

< href="javascript:function iptxt(){var d=document;try{if(!d.body)throw(0);window.location='http://www.instapaper.com/text?u='+encodeURIComponent(d.location.href);}catch(e){alert('Please wait until the page has loaded.');}}iptxt();void(0)">Go</a>

但我想在jquery中使用这段代码,如下所示:

<a href="#" id="go">Go</a>

以及将与id集成的jquery代码是什么。

感谢。

3 个答案:

答案 0 :(得分:3)

您只需将函数调用放入click

的callack中
<script>
$(function(){
    function iptxt(){
       var d=document;
       try{
         if(!d.body)throw(0);window.location='http://www.instapaper.com/text?u='+encodeURIComponent(d.location.href);
       } catch(e){alert('Please wait until the page has loaded.');}
    }

    $('#go').click(iptxt);
});
</script>

但这是最基本的jQuery任务。请查看jQuery tutorials

答案 1 :(得分:1)

试试这个

$("#go").click(function(){
    var d = document;
    try{
        if(!d.body){
            window.location = 'http://www.instapaper.com/text?u=' + encodeURIComponent(d.location.href);
        }
    }
    catch(e){
        alert('Please wait until the page has loaded.')
    }
})

答案 2 :(得分:0)

我不确定你为什么这样做if(!d.body)throw(0);对我没有多大意义。 但这是如何在jQuery中做的。

$("#go").click(function(event) {
     event.preventDefault();
     var d=document;
     try{
          if(!d.body)throw(0);
          window.location='http://www.instapaper.com/text?u='+encodeURIComponent(d.location.href);
     }catch(e){
          alert('Please wait until the page has loaded.');
     }
});