简体   繁体   English

这是调用javascript函数的正确方法吗?

[英]Is this a correct way to call a javascript function?

Is this the correct way to call my javascript function with jquery? 这是用jquery调用我的javascript函数的正确方法吗? I have spent the last 5 hours trying to figure out why this won't work. 我花了最后5个小时来弄清楚为什么这行不通。

<form class="rpt" id="rpt" action="">

$(function() {
  $("#rpt").submit(doSave);
});
</script>

Here is the small snippet of code in the javascript wysiwyg editor. 这是javascript wysiwyg编辑器中的一小段代码。 I'm still using the exact same form tag in my html. 我仍然在html中使用完全相同的表单标签。

        // Save
        case "Save":
            WYSIWYG.updateTextArea(n);
            var form = WYSIWYG_Core.findParentNode("FORM", this.getEditor(n));
            if(form == null) {
                alert("Can not submit the content, because no form element found.");
                return;
            }
            form.submit();
        break;

There are two variants of the submit function. 提交功能有两种变体。 If you call $('#rpt').submit(); 如果调用$('#rpt').submit(); you are firing the "submit" event of the form. 您正在触发表单的“提交”事件。 If you call $('#rpt').submit(myFunctionName); 如果调用$('#rpt').submit(myFunctionName); You are binding myFunctionName to the "submit" event of the form. 您将myFunctionName绑定到表单的“ submit”事件。 This will not be fired when the page loads, but only when you try to submit the form. 当页面加载时, 不会触发此操作,只有在您尝试提交表单时才会触发。 As such, this code: 因此,此代码:

<form id="rpt" method="GET" action="http://www.google.com/search">
Search: <input type="text" name="q"> <input type="submit" value="Go">
</form>

And this Javascript: 而这个JavaScript:

function myFunctionName() {
   alert('The form is being submitted!');
   return false; // cancel the event (ie, the form will not be sent)
}
$(function() {
    $('#rpt').submit(myFunctionName);
});

Will call the myFunctionName function only when the form is submitted (either by manually pressing the "Go" button or by pressing enter when the text field is focused). 仅在提交表单后才调用myFunctionName函数(通过手动按“转到”按钮或在文本字段为焦点时按Enter)。 Here is a sample of it at work . 这是工作示例 If you want to run a particular function when the page loads, all you have to do is pass something to the $(document).ready(); 如果要在页面加载时运行特定功能,则要做的就是将某些内容传递给$(document).ready(); function, or $() for short: 函数,或$()$()

function onLoadDoThis() {
    alert('Page is loaded!');
}
$(document).ready(onLoadDoThis); // $(onLoadDoThis); is the same thing

And here is an example of this . 这是一个例子 Hope this cleared some stuff up... 希望这可以清除一些东西...

EDIT 编辑

Ok, so I whipped up a working example of what you are trying to do. 好的,我整理了一个您要尝试做的工作示例。 At first I was annoyed you couldn't get this to work, but there were actually quite a number of limitations you have to work around because of how crappy this editor is. 起初,我很生气,您无法使用它,但是由于该编辑器的糟糕程度,实际上您必须解决很多限制。 Anyways, onto the explanation: 无论如何,要解释一下:

The first problem is that the library overrides the use of $ to its own little function. 第一个问题是该库将$的使用覆盖到其自己的小函数中。 So the jQuery awesomeness is not possible the regular way. 因此,jQuery绝妙的常规方法是不可能的。 Thankfully, jQuery is awesome and you can get around that by doing something like this: 幸运的是, jQuery非常棒 ,您可以通过执行以下操作来解决此问题:

$j = jQuery.noConflict();

Now instead of doing $(...); 现在不用做$(...); you have to do $j(...); 你必须做$j(...); . If you are not aware of this it is likely you were trying to write jQuery code and nothing was happening. 如果您不知道这一点,则很可能是您在尝试编写jQuery代码,但没有任何反应。

The next hurdle you were probably having is that for most events, when you do something like $(selector).myevent(aFunction); 您可能遇到的下一个障碍是,对于大多数事件,当您执行类似$(selector).myevent(aFunction); it is assumed that doing $(selector).myevent(); 假设正在做$(selector).myevent(); will fire said event. 将触发上述事件。 However, this is not true of the submit event . 但是, 对于commit事件并非如此 Unless the form action is triggered by a user the code you bind to the submit of a form won't be called when the form is submitted by code. 除非表单操作是由用户触发的,否则当您通过代码提交表单时,将不会调用您绑定到表单提交的代码。 So even though the line in the source code of the editor that does form.submit(); 因此,即使在编辑器的源代码中执行form.submit();也是form.submit(); is simply firing the native submit event of the form, even if you bind an event to this event with Javascript it won't be called in this circumstance because the user didn't trigger the submit event, code did. 只是触发了表单的本机提交事件,即使您使用Java脚本将事件绑定到此事件,在这种情况下也不会调用该事件,因为用户没有触发提交事件,而代码却触发了。

Due to this limitation, it gets increasingly tricky to achieve what you want without editing the source code of the editor. 由于此限制,在不编辑编辑器源代码的情况下实现所需的功能变得越来越棘手。 You see, the editor attaches its "create all the dashboard crap" stuff to the window's load event. 您会看到,编辑器将其“创建所有仪表板废话”内容附加到窗口的load事件。 This event fires after jQuery's DOM ready event, as the whole point of jQuery's ready is to fire as soon as possible and not a second later, while window.load takes its sweet time. 此事件在jQuery的DOM ready事件之后触发,因为jQuery的ready焦点是尽快触发,而不是一秒钟后触发,而window.load花了很长时间。 So what we have to do is ditch the jQuery bind code ( grimace ) and use the editor's own binding code to attach an event directly afterwards its own "create the dashboard" function. 因此,我们要做的是抛弃jQuery绑定代码( grimace ),并使用编辑器自己的绑定代码在事件自身的“创建仪表板”功能之后直接附加事件。 At this point, the dashboard has already been created so we can access the Save button and make it do what we want - only after removing its original event of calling the 'Save' function you found in the source code. 至此,仪表盘已经创建完毕,因此我们可以访问“保存”按钮并使它执行所需的操作-仅在删除调用源代码中的“保存”功能的原始事件之后。

At the end of the day, the code ends up looking like this: 最终,代码看起来像这样:

$j = jQuery.noConflict(); // give up ownership of $ to WYSIWYG

WYSIWYG.attach('textarea1', full); // first attach the event to create this widget

WYSIWYG_Core.addEvent(window, "load", function() {
    // and now override the Save button
    // the removeAttr('onclick') is crucial to stop it
    // from doing what it normally does (Which is submit the form)
    $j('#Save').removeAttr('onclick').click(function() {
        var form = $j('#myform');
        var data = form.serialize();
        var type = form.attr('method');
        var url = form.attr('action');
        $j.ajax({
            url: url,
            type: type,
            data: data,
            dataType: 'json',
            success: function(d) {
                if(d.success == 1) {
                    $j('#notice').html('Everything went alright! High fives.');
                } else {
                    $j('#notice').html('Something went wrong. Eep.');
                }
            }
        });        
    });
});

While my_handler.php is a very simple script that just returns a json string: 尽管my_handler.php是一个非常简单的脚本,仅返回json字符串:

<?php
// process your stuff here, set success as 1 or 0
$success = 1;
print json_encode(array('success' => $success));
?>

And here is an example of it in action . 这是一个实际的例子

Personally, I really don't like this particular editor and I would suggest you check out something else. 就个人而言,我真的不喜欢这个特定的编辑器,建议您检查其他内容。

Either way, though, I hope this helped. 无论哪种方式,我都希望能有所帮助。

Since "rpt" is the name of the class and the name of the form, you could use "." 由于“ rpt”是类的名称和表单的名称,因此可以使用“”。 or "#" and it will work assuming "doSave" is the name of a function to be used as a callback. 或“#”,并且假定“ doSave”是用作回调的函数的名称,它将起作用。 So, it can be called like this: 因此,可以这样称呼它:

$(".rpt").submit(doSave);
function doSave(){
  //do something
}

or you can have the function itself can be the parameter: 或者您可以让函数本身成为参数:

$(".rpt").submit(function(){
  //do something here
});

EDIT: If you don't want the form to postback. 编辑:如果您不希望表单回发。 Add a "return false;". 添加一个“返回false;”。

$("#rpt").submit(doSave);
function doSave(){
  //do something
  alert("form submit fired");
  return false;
}

It's even simpler than that: 比这更简单:

$("#rpt").submit(doSave);

If that doesn't work, it's because you work with a JQuery set, even though you are interested in submitting the form element. 如果这不起作用,那是因为即使您有兴趣提交form元素,您也可以使用JQuery集。 If so, try convincing JQuery that it's only a single element: 如果是这样,请尝试说服JQuery它只是一个元素:

$("#rpt").eq(0).submit(doSave);

It's possible that the doSave function must be defined earlier in source than the code binding it to the submit event... 有可能必须在源代码中定义doSave函数,而不是将其绑定到doSave事件的代码。

This code does NOT work 此代码不起作用

// doSave is undefined at this point
$("#rpt").submit(doSave);

// Now we've defined doSave, but it's too late.
function doSave(){
  //do something
  alert("form submit fired");
  return false;
}

I believe this code ought to work: 我认为这段代码应该有效:

$("#rpt").submit( function (){
    alert("submitted");
    return false;    
});

Or if you must define doSave separately, try this: 或者,如果您必须单独定义doSave,请尝试以下操作:

// First define doSave
function doSave(){
  //do something
  alert("form submit fired");
  return false;
}

// Then bind it
$("#rpt").submit(doSave);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM