通过锚识别表单提交动作

Recognize form submission action by anchor

■ 背景:

我有一个如下所示的 html,它有 1 个按钮、2 个锚点和一个用于保存包装在表单中的值的输入。 我想达到的目标是:

  1. 无论是点击按钮还是锚点,都可以提交表单。
  2. 使用 post.
  3. 能够识别哪个元素导致提交。(例如按钮 ID 或锚点 ID)

■ 问题:

我面临的问题是“由于锚点不可聚焦,如果触发提交,$(document.activeElement) 将无法识别它 通过单击锚点”(从 google 结果中学习...)。

■ 问题:

那么,是否有任何简单的(对我当前代码的更改较少)替代方法来实现我的目标,或者只是如何识别来自锚点的提交,以便我可以像我一样捕获它的信息 在这种情况下可以提交按钮吗?

谢谢

<form id="detailsForm" method="post" class="ui form" enctype="application/x-www-form-urlencoded" action="someUrl">

...
<button id="prodDelButton" form="detailsForm">
delete
</button>
...
<input type="text" id="pickupSearchCriteria.pageNumber" name="pickupSearchCriteria.pageNumber" value="1" />

<a class="item paginationAnchor" id="1" onclick="document.getElementById('detailsForm').submit();" shape="rect">page1</a>
<a class="item paginationAnchor" id="2" onclick="document.getElementById('detailsForm').submit();" shape="rect">page2</a>
...
...
</form>


...

<script id="shared_index_before">
    $('#detailsForm').submit(function () {

        var $btn = $(document.activeElement);
        if ($btn.prop('id') == 'stgDelButton') {
            $("#pickupSearchCriteria.pageNumber").val($btn.prop('id'));
        }
        else if ($btn.prop('id') == 'prodDelButton') {
            $("#pickupSearchCriteria.pageNumber").val($btn.prop('id'));
        }
        else if($btn.hasClass( "paginationAnchor" )){
            
            $("#pickupSearchCriteria.pageNumber").val($btn.prop('id'));
        }

    });
</script>

<form id="detailsForm" method="post" class="ui form" enctype="application/x-www-form- 
urlencoded" action="someUrl">

   <button class="submitableElement" id="prodDelButton" >
     delete
   </button>

   <input type="text" id="pickupSearchCriteria.pageNumber"name="pickupSearchCriteria.pageNumber" value="1" />

   <a class="item paginationAnchor submitableElement" id="1"  shape="rect">page1</a>
   <a class="item paginationAnchor submitableElement" id="2"  shape="rect">page2</a>

</form>

js:

$('.submitableElement').click(function(event){
   const id = event.target.id;
   doSomeThingWithId(id)//You can use the item id to know what was clicked.
   $('#detailsForm').submit()
 })



function doSomeThingWithId(id){
   alert(`Element with id ${id} was used to submit the form...`);  
   //Do something here with the data...
}

我认为这或多或少是您所需要的,但我建议您重新考虑您正在做的事情是否真的需要。

我的fiddle:https://jsfiddle.net/ku4rgqne/