jQuery更改表单的目标属性

11

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

<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>

你使用的 jQuery 版本是什么? - JohnP
你有什么问题吗?到目前为止,你说的是真的,这很好,但并没有引导任何事情。 - Till Helge
我在头文件中有这个代码:<script src="http://code.jquery.com/jquery-latest.js"></script> 我的问题是为什么它不起作用? - Martijn van den Broeck
@Martijn,如果您将代码放在“ready”处理程序中,它会更好地“工作”吗? - Frédéric Hamidi
2个回答

16
  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();
    
  2. If you're using jQuery > 1.6, you should be using prop() instead of attr(). For more details see StackOverflow: .prop() vs .attr()

    $("#select").change(function() {
        var targetvalue = /* which ever you decide */;
        $("#post_form").prop("target", targetvalue);
    });
    
  3. 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>
    
  4. 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>
    

0
如果您的HTML页面确实按照问题中指定的方式编写,那么脚本将在DOM更新为您要修改的表单后运行 - 但是,如果脚本是链接在

1
如果问题中所示的情况是这样的,那就没有必要了。只要script块在文档源代码中select框的下方,即使在jQuery的ready事件触发之前,select框也会存在并且可访问。请参见Google Closure库工程师在此主题上的留言 - T.J. Crowder

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接