使用javascript时停止刷新表单提交

时间:2017-10-20 06:24:57

标签: javascript html forms

我有一个受此method for encoding svg files as data uri's启发的简单表单。

表单提交由vanilla Javascript处理并且工作正常,除了页面得到刷新提交,我必须返回才能获得结果。如何停止页面刷新?

<body>
<form id="svgUriEncode">
    <textarea rows="4" cols="50" id="svgIn"></textarea>
    <button id="encode">encode</button>
    <textarea rows="4" cols="50" id="svgOut"></textarea>
</form>
<script type="text/javascript">

    var form = document.getElementById("svgUriEncode");

    function encodeOptimizedSVGDataUri(form) {
        var uriPayload = encodeURIComponent(form.svgIn.value) // encode URL-unsafe characters
        .replace(/%0A/g, '') // remove newlines
        .replace(/%20/g, ' ') // put spaces back in
        .replace(/%3D/g, '=') // ditto equals signs
        .replace(/%3A/g, ':') // ditto colons
        .replace(/%2F/g, '/') // ditto slashes
        .replace(/%22/g, "'"); // replace quotes with apostrophes (may break certain SVGs)

        form.svgOut.value = 'data:image/svg+xml,' + uriPayload;
    }


    form.encode.addEventListener("click", function () {
      encodeOptimizedSVGDataUri(form);
    });

</script>

2 个答案:

答案 0 :(得分:1)

添加类型=&#34;按钮&#34; ...否则会将其视为类型=&#34;提交&#34;因此页面刷新

 <button  type ='button' id="encode">encode</button>

答案 1 :(得分:0)

我建议您使用&#34;提交&#34;而不是点击&#34;点击&#34;这样你就可以捕获所有提交事件,不仅点击按钮,然后在事件上调用preventDefault以避免页面重新加载;)

&#13;
&#13;
var form = document.getElementById("svgUriEncode");

    function encodeOptimizedSVGDataUri(form) {
        var uriPayload = encodeURIComponent(form.svgIn.value) // encode URL-unsafe characters
        .replace(/%0A/g, '') // remove newlines
        .replace(/%20/g, ' ') // put spaces back in
        .replace(/%3D/g, '=') // ditto equals signs
        .replace(/%3A/g, ':') // ditto colons
        .replace(/%2F/g, '/') // ditto slashes
        .replace(/%22/g, "'"); // replace quotes with apostrophes (may break certain SVGs)

        form.svgOut.value = 'data:image/svg+xml,' + uriPayload;
    }


    form.addEventListener("submit", function (evt) {
      evt.preventDefault();
      encodeOptimizedSVGDataUri(form);
    });
&#13;
<form id="svgUriEncode">
    <textarea rows="4" cols="50" id="svgIn"></textarea>
    <button type="submit" id="encode">encode</button>
    <textarea rows="4" cols="50" id="svgOut"></textarea>
</form>
&#13;
&#13;
&#13;