【发布时间】:2017-11-03 14:45:53
【问题描述】:
我在一个 html 页面中有两个链接。当用户单击其中一个链接时,我想获取链接的 ID 并将其与表单数据一起提交。
我的html页面是这样的:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript">
var selectedForm = 0;
window.onload = function() {
$(".respondButton").on('click', function(e) {
var selectedButton = $(this).attr('id');
selectedForm = selectedButton.replace('response', '');
console.log(selectedForm);
});
document.getElementById("submitButton1").onclick = function() {
doWork()
};
}
function doWork() {
var response = $('#reply1').val();
console.log(response);
$.post({url: "receiver", data: JSON.stringify({selectedForm: selectedForm, response : response}),
contentType: "application/json", success: function(){}});
event.preventDefault();
}
</script>
This will send data using AJAX to Python:<br /><br />
<a id="response1" href="" class="respondButton">
<span>response1</span>
</a>
<a id="response2" href="" class="respondButton">
<span>response2</span>
</a>
<form action="/receiver" method="post" id="form1" name="form1">
<textarea type="text" rows ="3" name="reply1" id="reply1"></textarea>
<button type="submit" name="submitButton1" id="submitButton1">Gönder</button>
</form>
当我单击其中一个链接时,输入一些表单数据并单击提交按钮 selectedForm 始终为 0。
如何获取点击链接的 id 并与表单数据一起提交。
更新:
使用后 $(document).ready(function() { });而不是 window.onload 它现在按预期工作。
【问题讨论】:
-
它对我来说工作正常,我得到
1点击响应1 和2点击响应2。您还需要在点击处理程序中阻止这些链接 (e.preventDefault()) 上的默认行为。我也会使用$(document).ready(function() { });而不是window.onload。
标签: jquery