JS 日历完全启动后,会出现下面的 HTML,我想使用 AsynchronousViewDefault_CalendarView
属性运行我的 JS。然而,它根本不起作用。
否则,是否有任何解决方案可以解决我需要确保可以使用 AsynchronousViewDefault_CalendarView
属性来运行我的 JS 的问题?
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></div></div>
Javascript:
$( "#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');
}
);
});
或
$( "#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');
}
);
});
最佳答案
当您运行该选择器时,
#AsynchronousViewDefault_CalendarView div div table
不存在,因此也没有 on
元素来绑定(bind)事件处理程序,而是您应该将其委托(delegate)给祖先,例如 document
,或者该 html 被插入到的元素:
$(document).on(
"click",
"#AsynchronousViewDefault_CalendarView .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');
}
);
}
);
jQuery docs对此有很好的解释。 :
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next.
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.
关于javascript - 如何使用 Javascript 运行带有 on() 函数的 JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23259578/