Jquery改变表单的目标 [英] Jquery to change a form's target

查看:79
本文介绍了Jquery改变表单的目标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据所选的选项更改表单的目标。

I want to change the form's target based on the option which is selected.

<form id='post_form' target="targetvalue">

<select id="select" name="select">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>

    </form>


 <script>
 $("#select").change(function() {
    var targetvalue = $("#select option:selected").text();
    $("#post_form").attr("target", targetvalue);
    });

 </script>


推荐答案


  1. 您要将目标设置为选项1 选项2 ,你有什么是正确的。但是,如果您要将目标设置为 option1 option2 ,您应该有:

  1. If you want to set the target to either Option 1 or Option 2, what you have is correct. However, if you want to set the target to either option1 or option2, you should have:

var targetvalue = $("#select option:selected").val();

可简化为

which can be simplified to just;

var targetvalue = $(this).val();


  • 如果您使用jQuery> 1.6,则应该使用 prop() 而不是 attr() 。有关更多详细信息,请参阅StackOverflow: .prop()vs .attr()

    $("#select").change(function() {
        var targetvalue = /* which ever you decide */;
        $("#post_form").prop("target", targetvalue);
    });
    


  • 您不应该仅仅链接到最新生产环境中的版本;如果新版本的jQuery在发生重大更改时发布,那么就搞砸了。链接到特定版本的jQuery,并在升级到新版本之前进行彻底测试;

  • You shouldn't really be linking to just the latest version in a production environment; if a new version of jQuery gets released with breaking changes, you're screwed. Link to a specific version of jQuery, and test thoroughly before you upgrade to a new release;

    <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    


  • 如果您仅 < form> 元素之后的c>< script> 能够实现它,意识到您可以使用 $(document).ready() block来随时定义脚本;

  • If you're only defining the <script> after the <form> element to be able to target it, realise you can use a $(document).ready() block to define the script anywhere;

    <script>
        $(document).ready(function () {
            $('#select').change(function () {
                var targetvalue = /* which ever you decide */;
                $('#post_form').prop("target", targetvalue);
            });
        });
    </script>
    


  • 这篇关于Jquery改变表单的目标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆