[英]Change attribute value for event only
我有這個基本形式:
jQuery(document).ready(function($) { $('#btn').click(function() { var form = document.getElementById('form'); form.setAttribute('action', 'export.php'); form.submit() }) })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form method="post" action="get.php" id="form"> <div> <label for="date">From</label> <input type="date" name="from-date" id="date" /> </div> <div> <label for="date">To</label> <input type="date" name="to-date" id="date" /> </div> <div> <input type="checkbox" name="flags[new]" /> New <input type="checkbox" name="flags[updated]" /> Updated <input type="checkbox" name="flags[existing]" /> Existing </div> <div> <input type="submit" /> </div> <div> <button type="button" id="btn"> <span>Export</span> </button> </div> </form>
如預期的那樣工作。 但是,然后我單擊了提交輸入,並嘗試進入export.php
。 由於某種原因,我的大腦告訴我這是不正確的行為,但是我知道我已經更改了DOM中的屬性值,因此,單擊導出按鈕后進行的任何操作都將呈現該屬性值(直到刷新)。
我知道我可以做另一個事件處理程序來重置屬性值,但是我覺得這是違反直覺的,JS / jQuery中是否有某些東西允許我僅“切換”事件的屬性? 還是我必須進行硬重置?
TL; DR
是否可以在事件中臨時設置屬性?
嘗試這樣的事情:
jQuery(document).ready(function($) {
$('#btn').click(function() {
let form = document.getElementById('form');
//Save the current attr
let currentAttr = form.getAttribute('action');
form.setAttribute('action', 'export.php');
form.submit();
//Reset the previous attr
form.setAttribute('action', currentAttr);
})
})
您實際上保存了當前的attr,提交了表單,然后將屬性設置為原始屬性。
希望它能解決您的問題!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.