从模块内部引用特定的表单元素

Referencing a specific form element from inside a module

本文关键字:表单 元素 模块 内部 引用      更新时间:2023-09-26

我正试图弄清楚如何在模块内部引用表单。

模块如下所示:

const UserShows = (function(){
  const saveShowToDashboard = function(evt) {
    evt.preventDefault();
    const $saveShowForm = $(this);
    setTimeout(function() {
      $saveShowForm.children('.save-show-btn').val('Saved');
    }, 500);
    const showInfo = $(this).children('.save-show-checkbox').val();
    const parsedShowInfo = JSON.parse(showInfo);
    const _csrf = $(this).children('.csrf').val();
    const artistName = parsedShowInfo.artist;
    const data = {
      showInfo: parsedShowInfo,
      _csrf: _csrf,
    };
    console.log(data);
    $.post('/artists/' + artistName, data, function(res) {
      if (res === '/login') {
        window.location = res;
      }else{
        console.log(res);
      }
    });
  };
  return {
    callSaveShowToDashboard: function(evt){
      return saveShowToDashboard(evt);
    }  
  }
})();
// Call saveShowToDashboard on click
$('.save-show').on('submit', UserShows.callSaveShowToDashboard);

我遇到的问题是,我不知道如何引用正在提交的特定保存展览表格(页面上有几个表格;每个表格对应一个艺术家巡演日期)。

在我决定将此函数放入UserShows模块之前,我可以使用$(this)来引用特定的表单,但由于该表单不再是该函数的直接调用方,因此它不起作用。

事实证明,使用JQuery,您可以使用event.target引用触发事件的元素。因此,如果我像这样重写代码,它会起作用:

const saveShowToDashboard = function(evt) {
    evt.preventDefault();
    const $saveShowForm = $(event.target);
    setTimeout(function() {
      $saveShowForm.children('.save-show-btn').val('Saved');
    }, 500);
    const showInfo = $saveShowForm.children('.save-show-checkbox').val();
    const parsedShowInfo = JSON.parse(showInfo);
    const _csrf = $saveShowForm.children('.csrf').val();
    const artistName = parsedShowInfo.artist;
    const data = {
      showInfo: parsedShowInfo,
      _csrf: _csrf,
    };
    console.log(data);
    $.post('/artists/' + artistName, data, function(res) {
      if (res === '/login') {
        window.location = res;
      }else{
        console.log(res);
      }
    });
  };