如何将元素ID传递给我的jQuery函数

时间:2010-06-24 22:17:44

标签: jquery coldfusion

我正在将Ben Nadel的iFrame上传功能用于我正在处理的网站上的编辑工具。我正在学习jQuery。该功能非常有效。它是可重复使用的模态窗口的一部分,一切正常。但是,我想动态地告诉调用来自哪里的函数,所以它将正确的形式加载到模态窗口中。我将如何将其传递给函数。现在,它已被硬编码为#uploadform接收。本质上,我想重新使用该函数并放入变量,如动作,预览和表单ID等......

$(function(){
                var jForm = $( "#uploadform" );
                jForm.submit(
                    function( objEvent ){
                    var jThis = $( this );
                    var strName = ("uploader" + (new Date()).getTime());
                    var jFrame = $( "<iframe name=\"" + strName + "\" src=\"about:blank\" />" );
                    jFrame.css( "display", "none" );
                    jFrame.load(
                        function( objEvent ){
                            var objUploadBody = window.frames[ strName ].document.getElementsByTagName( "body" )[ 0 ];
                            var jBody = $( objUploadBody );
                            var objData = eval( "(" + jBody.html() + ")" )
                            var thumb = ('thumbnails/' + eval(jBody.html()));
                            $("#header").css("background", "url(" + thumb + ") no-repeat center");
                            $("#preview").attr("src", thumb);
                    setTimeout(
                        function(){
                            jFrame.remove();
                            },100);
                });
            $( "body:first" ).append( jFrame );
            jThis
                .attr( "action", "upload_act_single.cfm" )
                .attr( "method", "post" )
                .attr( "enctype", "multipart/form-data" )
                .attr( "encoding", "multipart/form-data" )
                .attr( "target", strName );
            });
        });

3 个答案:

答案 0 :(得分:4)

我打算提出类似的建议,除了为这个场合创建一个单独的函数:

function formSubmit(formId) {
   var jForm = $("#"+formId);
   //remainder of your code
}

接下来,对于每个表单,在声明html表单时直接创建onSubmit连接:

<form id="myForm" class="pageForms" onsubmit="function(formSubmit(this.id))> ...

或以编程方式:

$("#myForm").submit(function() {
   formSubmit("#myForm");
});

[OR]

$(".pageForms").submit(function() { //to apply to all forms within the document
    formSubmit("#"+this.id);         //with that class
});

对于文档中的所有表单(但不确定它是否有效)

$("form").submit(function() { 
   formSubmit("#"+this.id);
});

请记住在onLoad函数[$(function(){...})]中执行附件,否则可能会发生javascript错误:S

答案 1 :(得分:0)

尝试$(this).attr("id")

答案 2 :(得分:0)

var myFunction = function(formid) {
  var jForm = $( formid );
  // ....
}

$(function() {
  myFunction("#uploadform");
});
$(function() {
  myFunction("#uploadform2");
});