加载选择元素时的 JQuery 事件处理程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17297764/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:46:43  来源:igfitidea点击:

JQuery event handler when select element is loaded

javascriptjquerydomjavascript-events

提问by Einar Sundgren

Is there an event handler to use in JQuery when a DOM selectelement has finished loading? This is what I want to achieve. It is working with other events except 'load'.

当 DOM选择元素完成加载时,是否有在 JQuery 中使用的事件处理程序?这就是我想要达到的目标。它正在处理除“加载”之外的其他事件。

This piece of code is loaded in the head.

这段代码加载在头部。

$(document).on('load', 'select', function(){
    var currentSelectVal = $(this).val();
    alert(currentSelectVal);
    } );

The question was badly formed earlier. I need to attach the event handler to all selectelements, both present when the document is loaded and dynamically created later.

这个问题早些时候形成的很糟糕。我需要将事件处理程序附加到所有选择元素,这两个元素都在加载文档时出现并在以后动态创建。

They are loaded from a JQuery Post to a php-page. Similar to this:

它们从 JQuery Post 加载到 php 页面。与此类似:

$.post("./user_functions.php", 
{reason: "get_users", userID: uID}) 
.done(function(data) { $("#userSelector").html(data);
 }); 

回答by SpYk3HH

I think we're all confused. But a quick break down of your options.
After an update made to the Question, it looks like the answer you might seek is my last example. Please consider all other information as well though, as it might help you determine a better process for your "End Goal".

我想我们都糊涂了。但是快速分解您的选择。
对问题进行更新后,您可能寻求的答案似乎是我的最后一个示例。不过,请考虑所有其他信息,因为它可能会帮助您为“最终目标”确定更好的流程。

First, You have the DOM Load event as pointed out in another answer. This will trigger when the page is finished loading and should always be your first call in HEAD JavaScript. to learn more, please see this API Documentation.

首先,您有另一个答案中指出的 DOM Load 事件。这将在页面加载完成时触发,并且应该始终是您在 HEAD JavaScript 中的第一次调用。要了解更多信息,请参阅此 API 文档

Example

例子

$(document).ready(function () {
    alert($('select').val());
})
/*  |OR|    */
$(function() {
    alert($('select').val());
})

Then you have Events you can attach to the Select Element, such as "change", "keyup", "keydown", etc... The usual event bindings are on "change" and "keyup" as these 2 are the most common end events taking action in which the user expects "change". To learn more please read about jQuery's .delegate()(out-dated ver 1.6 and below only), .on(), .change(), and .keyup().

然后你有可以附加到选择元素的事件,例如“change”、“keyup”、“keydown”等......通常的事件绑定是“change”和“keyup”,因为这两个是最常见的结束事件采取用户期望“改变”的行动。要了解更多信息,请阅读 jQuery 的.delegate()(仅限 1.6 及以下版本过时)、.on().change().keyup()

Example

例子

$(document).on('change keyup', 'select', function(e) {
    var currentSelectVal = $(this).val();
    alert(currentSelectVal);
}) 

Now delegatingthe change event to the document is not "necessary", however, it can really save headache down the road. Delegating allow future Elements (stuff not loaded on DOM Load event), that meet the Selector qualifications (exp. 'select', '#elementID', or '.element-class') to automatically have these event methods assigned to them.

现在delegating对文档的更改事件不是“必需的”,但是,它确实可以省去头疼的麻烦。委托允许未来元素(未在 DOM Load 事件上加载的东西)满足选择器限定条件(exp. 'select'、'#elementID' 或 '.element-class')自动将这些事件方法分配给它们。

However, if you know this is not going to be an issue, then you can use event names as jQuery Element Object Methods with a little shorter code.

但是,如果您知道这不会成为问题,那么您可以使用更短的代码将事件名称用作 jQuery 元素对象方法。

Example

例子

$('select').change(function(e) {
    var currentSelectVal = $(this).val();
    alert(currentSelectVal);
}) 

On a final note, there is also the "success" and "complete" events that take place during some Ajax call. All jQuery Ajax methods have these 2 events in one way or another. These events allow you to perform action after the Ajax call is complete.

最后,还有一些 Ajax 调用期间发生的“成功”和“完成”事件。所有 jQuery Ajax 方法都以一种或另一种方式具有这两个事件。这些事件允许您在 Ajax 调用完成后执行操作。

For example, if you wanted to get the value of a select box AFTER and Ajax call was made.

例如,如果您想在进行 Ajax 调用后获取选择框的值。

Example

例子

$.ajax({
    url: 'http://www.mysite.com/ajax.php',
    succuess: function(data) {
        alert($("select#MyID").val());
    }
})
/*  |OR|    */
$.post("example.php", function() { alert("success"); })
.done(function() { alert($("select#MyID").val()); })
/*  |OR|    */
$("#element").load("example.php", function(response, status, xhr) {
    alert($("select#MyID").val());
});

More reading:

更多阅读:

Something else to keep in mind, all jQuery Ajax methods (like .get, .post) are just shorthand versions of $.ajax({ /* options|callbacks */ })!

还有一点要记住,所有 jQuery Ajax 方法(如 .get、.post)都只是$.ajax({ /* options|callbacks */ })!

回答by reyaner

Why dont you just use:

你为什么不使用:

$(document).ready(function () {
   //Loaded...
});

Or am I missing something?

或者我错过了什么?

回答by George

For your dynamic selects you can put the alert in the callback.

对于您的动态,select您可以将警报放在回调中。

In your .post()callback function, try this:

在您的.post()回调函数中,试试这个:

.done(function(data) {
    data = $(data);
    alert(data.find("select").val());
});

回答by reggaemahn

Ok, correct me if I understand this wrong. So you want to do something with the selects when the document is loaded and also after you get some fresh data via an ajax call. Here is how you could accomplish this.

好的,如果我理解错误,请纠正我。因此,您希望在加载文档时以及通过 ajax 调用获取一些新数据后对选择执行某些操作。以下是您如何完成此操作。

First do it when the document loads, so,

首先在文档加载时执行,因此,

<script>
//This is the function that does what you want to do with the select lists
function alterSelects(){
 //Your code here
}
  $(function(){
      $("select").each(function(){
           alterSelects();
      });
  });
</script>

Now everytime you have an ajax request the ajaxSend and ajaxComplete functions are called. So, add this after the above:

现在每次有 ajax 请求时都会调用 ajaxSend 和 ajaxComplete 函数。所以,在上面添加这个:

$(document).ajaxSend(function () {
}).ajaxComplete(function () {
    alterSelects();
});

The above code will fire as soon as the request is complete. But I think you probably want to do it after you do something with the results you get back from the ajax call. You'll have to do it in your $.post like this:

一旦请求完成,上面的代码就会触发。但是我认为您可能想在对从 ajax 调用中得到的结果做一些事情之后再做。你必须在你的 $.post 中这样做:

$.post("yourLink", "parameters to send", function(result){
    // Do your stuff here
    alterSelects();
});

回答by reyaner

Do you want all Selects to be checked when the User-Select is loaded, or just the User-Select?...

您希望在加载用户选择时检查所有选择,还是仅检查用户选择?...

$.post("./user_functions.php", {reason: "get_users", userID: uID}).done(function(data) {  
    $("#userSelector").html(data);
    //Then this:
    var currentSelectVal = $("#userSelector").val();
    alert(currentSelectVal);
});

回答by zen.c

My solution is a little similar to the posters above but to use the observer (pubsub) pattern. You can google for various pub sub libraries out there or you could use jQuery's custom events. The idea is to subscribe to a topic / custom event and run the function that attach the event. Of course, it will be best to filter out those elements that have been initialize before. I havent test the following codes but hopefully you get the idea.

我的解决方案与上面的海报有点相似,但使用了观察者(pubsub)模式。您可以在那里搜索各种 pub 子库,也可以使用 jQuery 的自定义事件。这个想法是订阅主题/自定义事件并运行附加事件的函数。当然,最好过滤掉那些之前已经初始化过的元素。我还没有测试以下代码,但希望你能明白。

function attachEventsToSelect(html) {
    if (!html) { // html is undefined, we loop through the entire DOM we have currently
        $('select').doSomething();
    } else {
        $(html).find('select').doSomething(); // Only apply to the newly added HTML DOM
    }
}

$(window).on('HTML.Inserted', attachEventsToSelect);

// On your ajax call
$.ajax({
    success: function(htmlResponse) {
        $(window).trigger('HTML.Inserted', htmlResponse);
    }
});

// On your DOM ready event
$(function() {
    $(window).trigger('HTML.Inserted'); // For the current set of HTML
});

回答by Michael Blancaflor

If your select elements are dynamically loaded, why not add the event handler after you process the response?

如果您的选择元素是动态加载的,为什么不在处理响应后添加事件处理程序?

e.g. for ajax

例如对于 ajax

$.ajax({
  ...
  success: function(response) {
   //do stuff 
   //add the select elements from response to the DOM 
   //addMyEventHandlerForNewSelect();

   //or

   //select the new select elements from response
   //add event handling on selected new elements
  },
  ...
});