代码之家  ›  专栏  ›  技术社区  ›  zaozaoer

通过锚识别表单提交操作

  •  1
  • zaozaoer  · 技术社区  · 6 年前

    背景:

    我想实现的目标是:

    1. 无论单击按钮和锚定按钮,都可以提交表单。
    2. 使用post。
    3. 能够识别导致提交的元素(例如按钮id或锚id)

    问题:

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

    问题:

    在这种情况下,您可以提交按钮吗?

    谢谢

    <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>
    1 回复  |  直到 6 年前
        1
  •  1
  •   i.brod    6 年前
    <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...
    }
    

    我认为这或多或少是你需要的,但我建议你重新考虑一下你在那里做的事情是否真的需要。

    我的小提琴: https://jsfiddle.net/ku4rgqne/