简体   繁体   中英

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.

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.

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.

I'm using the "PickMeUp" datepicker plugin.

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 .

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:

$("#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.

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?

$("#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/

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.

Also, ".click" is just an alias for ".on", so you can use either.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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