How to let the Javascript run at the last process

2019-07-02 15:00发布

问题:

I got into a trouble that when the Page Loads, then my Javascript runs and the JS Calendar loads after my JS. Thus, my JS doesn't affect to JS Calendar.

1.Page Loads

2.My JS runs

3.Something (Other JS) goes here

4.JS Calendar starts

What I want here is to let my JS runs after the JS Calendar. Some suggested me to use on() but I don't know that is the best solution or there are other solutions.

The JSFIDDLE below works very well with browsers but it doesn't work with SharePoint 2010.

HTML:

<div id="AsynchronousViewDefault_CalendarView">
<div class="ms-acal-header">
<div>
    <table class="ms-acal-month">
    </table>
    <div class="ms-acal-vlink">
        <table>
            <tbody>
                <tr>
                    <td><a href="javascript:void(0)" title="Add" evtid="new_item">
                        <img border="0" src="/_layouts/images/caladd.gif">Add</a></td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

Javascript:

$(document).ready(function () {
        var abc = $("#AsynchronousViewDefault_CalendarView").find('a[title="Add"][evtid="new_item"]').hover(
          function () {
              $(this).attr('href', 'http://share/Lists/Calendar.aspx?P=P1');
          }
        );
    });

JSFIDDLE: http://jsfiddle.net/nALMw/

I have attempted with jQuery on() but It didn't work with my SharePoint 2010:

$( "#AsynchronousViewDefault_CalendarView div div table" ).on( "click", function() {
    var abc = $("#AsynchronousViewDefault_CalendarView").find('a[title="Add"] [evtid="new_item"]').hover(
        function () {
            $(this).attr('href', 'http://share/Lists/Calendar.aspx?P=P1');
        }
    );
});

or

$( "#AsynchronousViewDefault_CalendarView" ).on( "click", '.ms-acal-vlink' , function() {
    var abc = $("#AsynchronousViewDefault_CalendarView").find('a[title="Add"] [evtid="new_item"]').hover(
        function () {
            $(this).attr('href', 'http://share/Lists/Calendar.aspx?P=P1');
        }
    );
});

回答1:

Here is my solution, please let me know if it doesn't work with your SharePoint or anything goes wrong :-).

$(document).on("click", "#AsynchronousViewDefault_CalendarView .ms-acal-vlink", function () {
        var find_aTag = $(("#AsynchronousViewDefault_CalendarView").find('a[title="Add"]'));
        find_aTag.attr("href", "http://share/Lists/Calendar.aspx?P=P1");
    });

or MdMazzotti's method

_spBodyOnLoadFunctionNames.push("spReady");

function spReady() {
  $('.s4-ba').on('click', '.ms-acal-item a', function(){ 
     console.log('clicked');  
  });
}