简体   繁体   中英

Assigning global variable to following Javascript

How can we make the var modal = $("#modal"); a global variable?

Where we have the modal variable in the following code, we need it to work, it currently doesn't, var content = "Hello " + name + ", You have signed " + modal + " up to XYZ";

Many, many thanks!

$(document).ready(function() {
$('#calendar').fullCalendar({
  header: {
    left: '',
    center: 'title',
    right: 'prev,next today'
  },
  defaultDate: '2016-03-15',
  events: [

    {
      title: 'Event',
      start: '2016-03-26T11:00:00',
      end: '2016-03-26T12:00:00',
    },
  ],
  eventClick: function(event) {
    console.log(event)
      // alert(event.start.format('MMMM Do YYYY'))
    start = event.start.format('MMMM Do YYYY'),
      end = event.end.format('MMMM Do YYYY'),
      html = '<p>Starts: ' + start + '<p>';
    html += '<p>Ends: ' + end + '<p>';
    var modal = $("#modal");
    modal.find(".modal-title").html(event.title);
    modal.find('.modal-body').html(html)
    modal.modal();
  }
})



 $("#contact_form").submit(function() {
var email = $("#email").val(); // get email field value
var name = $("#name").val(); // get name field value
var msg = $("#msg").val(); // get message field value
var content = "Hello " + name + ", You have signed " + modal + " up to XYZ";
$.ajax({
    type: "POST",
    url: "https://mandrillapp.com/api/1.0/messages/send.json",
    data: {
      'key': 'api',
      'message': {
        'from_email': "email",
        'text': "Hello ",
        'from_name': "name",
        'headers': {
          'Reply-To': "email"
        },
        'subject': 'Confirmation - Sign Up',
        'text': content,
        'to': [{
          'email': email,
          'name': name,
          'type': 'to'
        }]

      }
    }

  })
  .done(function(response) {
    alert('You have been signed up. Thank you!'); // show success message
    $("#name").val(''); // reset field after successful submission
    $("#email").val(''); // reset field after successful submission
    $("#msg").val(''); // reset field after successful submission

  })
  .fail(function(response) {
    alert('Error sending message.');
  });
return false; // prevent page refresh
 });
});

The simple solution for making value global is:

window.modal = "Value";

If you actually don't really need it but just want to store it in a way, where multiple functions will have an access to it you can create it in the scope of the function like:

(function(){
    var modal = "value";

    $.ajax({
        success: function() {
             console.log(modal);
        }
    })
})()

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