0

感谢您的关注。

我仍在学习更复杂的 javascript 和 jquery 编码,因此可以提供一些帮助,因为我不知道以下内容,或者即使它可能!

我需要一种更好/更简单/更短的方法来执行以下操作(请注意我已经删除了不相关的验证等编码):'

function Findbox5( myform, box1, box2, box3, box4, box5, Storeall, s1, s2, s3, s4, s5)
   {
   //store values
     Myform = document.forms.myform;
     box1 = Myform.box1.value;
     box2 = Myform.box2.value;
     box3 = Myform.box3.value;
     box4 = Myform.box4.value;
     box5 = Myform.box5.value;
     s1 = Myform.s1.value;
     s2 = Myform.s2.value;
     s3 = Myform.s3.value;
     s4 = Myform.s4.value;
     s5 = Myform.s5.value;

     //set as one string

     Storeall = s1 + ":" + box1 + ";" + s2 + ":" + box2 + ";" + s3 + ":" + box3 + ";" + s4 + ":" + box4 + ";" + s4 + ":" + box5 + ";" ;

     // next function...

   } '

如您所见,我有 5 个输入框和每个框的相关选择(每个选择有 4 个选项:1、2、3、4。)。当用户在框中输入数据时,他们会选择相关选项。必须输入所有框和选项,然后他们才能提交表格。

此数据将作为存储在 storeall 下的变量通过电子邮件发送给我。这将类似于 1:1234;2:1324;1:3232;4:5434;2:3211;

所以我希望做的是使用单独的函数或相同的函数将这些数据简化为以下数据:1:1234-3232;2:1324-3211;4:5434;

这可能吗?还是我做了最简单的方法?

欢迎任何意见或帮助,再次感谢

4

2 回答 2

0

If you want everything in the form, you should use serializeArray :

$('#my_form').submit(function() {
  var str = '';
  $.each($(this).serializeArray(), function () {
      str += this.name + ":" + this.value + ";";
  });
  sendByMail(str);
  return false;
});
于 2011-12-02T23:19:27.060 回答
0

首先,您需要将这些东西组合成一个可以迭代的元素。因此,如果您的 HTML 看起来像:

<form>
    <input name="s1" />
    <input name="box1" />
    <input name="s2" />
    <input name="box2" />
    ...
</form>

那么最好做类似的事情:

<form>
    <div class="set">
        <input class="s" name="s1" />
        <input class="box" name="box1" />
    </div>
    <div class="set">
        <input class="s" name="s2" />
        <input class="box" name="box2" />
    </div>
    ...
</form>

现在您已经在这些元素之间建立了一些共性,而不仅仅是不同的名称/ID。每组输入都按.set类分组,在每组中,您知道将有两个输入:一个与.s类有关,一个与.box类有关。现在用 JQuery 对它们进行迭代很容易:

var str = "";
$("form div.set").each(
    function(index, element)
    {
        currentValueS = $(element).find("input.s").val();
        currentValueBox = $(element).find("input.box").val();
        str += currentValueS + ":" + currentValueBox + ";";
    }
);

这使用了 JQuery 的.each()功能。.each()允许您提供一个函数来对 JQuery 从指定选择器中找到的每个元素执行。在这里,您的选择器是form div.set,这意味着“所有div具有.set,并且在任何元素下的任何位置都可以找到的form元素”。对于这些元素中的每一个,您都需要找到具有类的<input>元素的值,以及具有类的元素.s的值。然后,您只需将它们添加到您不断增长的变量中。<input>.boxstr

于 2011-12-02T23:02:52.657 回答