将JS函数转换为使用jquery

时间:2012-05-25 19:44:10

标签: javascript jquery

我开始使用Jquery,我想用jquery制作以下JS函数 有人帮忙吗?

<script type="text/javascript" language="javascript">
function redirect() {

  //var dest = "?phone=" + phone;
  var prefill = "&prefill=3";
  var info=document.choice.infos.value;
  var dest = "&info="+info;
  var url=document.choice.centres.value;
  var urlfinal=url+dest+prefill;
  document.location.href=urlfinal
}
</script>


<form name="choice">    
<select name="centres">
  <option value="http://toto.com/?var=1">var1</option>
  <option value="http://toto.com/?var=2">var2</option>
</select>
<br />
<INPUT TYPE="text" NAME="infos">
<input type="button" value="Go!" onClick="redirect();">

</form>

2 个答案:

答案 0 :(得分:2)

您的按钮标记

<input type="button" value="Go!" id="submit">

和jquery代码:

$(document).ready(function() {
    $('#submit').click(function() {
        //var dest = "?phone=" + phone;

        var finalUrl = $("select#centers").val();
        var querystring = '&prefill=3' + '&info=' 
                               + $("select#info").val() + dest;
        finalUrl = finalUrl + querystring ;
        window.location.replace(finalUrl);
    });
});

答案 1 :(得分:0)

在Javascript控制台打开的情况下使用Google Chrome或Firefox,并养成使用console.log在关键点检查代码的习惯。 顺便说一句,您不需要表单元素:

...
<script type="text/javascript">
$(function () {

    $('#btnRedirect').click(function () {
        var centres = $('#centres');
        var centre = $('option:selected', centres);
        //console.log(centre.val());

        var infos = $('#infos');
        //console.log(infos.val());

        var dest = "&info=" + infos.val();
        var prefill = "&prefill=3";
        var urlfinal = centre.val() + dest + prefill;
        //console.log(urlfinal);

        document.location = urlfinal;
    });
});
</script>

...

<body>
<select id="centres">
  <option value="http://toto.com/?var=1">var1</option>
  <option value="http://toto.com/?var=2">var2</option>
</select>
<br />
<input type="text" id="infos"/>
<input id="btnRedirect" type="button" value="Go!"/>
</body>