简体   繁体   English

jQuery。 在动态加载的内容上绑定插件的实例

[英]Jquery. Binding the instantiation of a plugin on dynamically loaded content

Having a problem selecting an id within a dynamically placed div tag on a page. 在页面上动态放置的div标签内选择id时遇到问题。

It's a date field and I'd like to have a datepicker show up when the user focuses on the field. 这是一个日期字段,当用户专注于该字段时,我想显示一个日期选择器。 That I'm trying to set up a plugin instead of doing any other kind of jQuery event is, I think, my problem. 我想我要设置一个插件而不是执行任何其他类型的jQuery事件是我的问题。

So here's the dynamically loaded content that is placed on the page when a user clicks one of several radio buttons in a "calendar". 因此,这是当用户单击“日历”中的几个单选按钮之一时动态放置的内容的页面。

$("#s10").click(function(){
    $("#S_Date").html('<input type="text" name="Start_Date" id="Start_Date" value="2016-05-24" />2016-05-24');

#S_Date is the parent div id that is loaded when the document loads. #S_Date是加载文档时加载的父div ID。

I'm using the "PickMeUp" datepicker plugin. 我正在使用“ PickMeUp”日期选择器插件。

From what I can tell, I need to use the on() event handler but I just can't seem to get it to bind to #Start_Date . 据我所知,我需要使用on()事件处理程序,但似乎无法将其绑定到#Start_Date

Here's my latest attempt at trying to call it: 这是我最近尝试调用它的尝试:

var pickitup = $("#Start_Date").pickmeup({format  : 'Y-m-d'});
$("#S_Date").on('focus', "#Start_Date", function(){pickitup});

With pickitup defined, I have also tried: 在定义了pickitup之后,我还尝试了:

$("#S_Date").on('focus', "#Start_Date", pickitup);

$("#S_Date").on('focus', "#Start_Date", function(){pickmeup({format : 'Ym-d'})}); fails out of the gate with a pickmeup is not defined error. 发生故障,但pickmeup is not defined错误。

Ideas anyone? 有任何想法吗?

So, if I'm understanding what you're doing, you want to insert some html into a given element on that click event, then apply the date picker functionality to it? 因此,如果我了解您的操作,是否要在该click事件的给定元素中插入一些html,然后对其应用日期选择器功能?

$("#s10").on("click", function() { //when the element is clicked...
  //create an input with the appropriate attributes
  var picker = $("<input />", { type: "text", name: "Start_Date", value: "2016-05-24" }); 
  //append it to the desired element(s)
  $("#S_Date").append(picker);
  //run the plugin on it
  picker.pickmeup({format: 'Y-m-d'});
});

Here's a working (simple) fiddle https://jsfiddle.net/s6vu0rnq/ 这是一个工作(简单)的小提琴https://jsfiddle.net/s6vu0rnq/

The undefined error you got was because "pickmeup" is a property of jquery's prototype, but you were trying to call it from the global scope. 您收到的未定义错误是因为“ pickmeup”是jquery原型的属性,但是您试图从全局范围调用它。

Also, ".click" is just an alias for ".on", so you can use either. 另外,“。click”只是“ .on”的别名,因此您可以使用其中任何一个。

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

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