jQuery找到所有按钮并单击

时间:2014-11-29 16:41:26

标签: javascript jquery html

我有一个javascript片段,它为我添加的文件呈现单个按钮,如下所示单独上传

data.context = $('<button name=uploadFile/>').text('Start Individual Upload')
    .appendTo(document.body)
                .click(function () {
                    // code to do individual upload (removed for brevity)
                });

如果我选择了3个文件,则呈现标记例如:

<button name="uploadFile">Start Upload</button>
<button name="uploadFile">Start Upload</button>
<button name="uploadFile">Start Upload</button>

如果我单独点击每个按钮,将调用点击处理程序,文件将上传。

我现在想要尝试的是一个上传所有按钮,我可以添加到我的html,然后在上传所有按钮上点击处理函数,触发每个单独上传按钮的点击处理程序(即 - 模仿用户点击每个开始上传按钮?

 <input id="uploadAllFiles" type="button">

$('#uploadAllFiles').on("click", function () {
    // not sure what to do here to find all buttons with name = uploadFile and trigger clicking     them
});

2 个答案:

答案 0 :(得分:1)

单击uploadAllFiles按钮时,单击名称为uploadFile

的每个按钮
$('#uploadAllFiles').on("click", function() {
    //This will click each of the buttons with the
    //attribute name set to "uploadFile"
    $('button[name="uploadFile"]').click()
});

答案 1 :(得分:0)

好的,有可能因为回答而不是问题而被击落,但潜在的动机......

我不这样做。按钮单击处理程序只是一个UI界面,准控制器,用于启动业务逻辑,即上传文件。相反,我会将逻辑隔离到sepaarte函数中,让每个click处理程序调用它的函数,upload-all将它们全部调用。

有点像这样:

data.context = $('<button name=uploadFile/>').text('Start Individual Upload')
.appendTo(document.body)
            .click(createClickHandler(fileName)); // assuming filename is the name of the file to upload

createClickHandler的位置:

var allfiles = [];
var createClickHandler = function(filename) {
  var fileupload = function() {
    // upload file logic referencing "filename" var
  }, handler = function() {
   // click handler logic
   fileupload();
  };
  allfiles.push(fileupload);
  return(handler);
};

现在当有人点击全部加载时:

.click(function() {
   $.each(allfiles,function(f) {
     f();
   });
});