1
首先,简单介绍一下我的设置。
我有一个全球JS文件common.js,其中我存储所有常用的功能。该文件被捆绑并设置为与_Layout.cshtml视图文件一起加载。
伴随于此,我有一个视图文件,其产生一个HTML对象像以下:通过扩展的方法
@section scripts {
@Html.LoadVersionedJavascriptFile("~/location/sourcefile.js")
}
<a class="printreport" href="#" data-reporttype="8" data-certid="1111">Print</a>
提到视图文件加载的JavaScript源文件为了优化我的代码,我决定写一个片段函数,这将使每个具有“printreport”类的html对象运行它
内部源文件:
$(function(){
//other stuff
//Every html object that has printreport as a class will run this function
$(document.body).on('click', '.printreport', function() {
//get reporttype data from object
var reportType = $(this).data('reporttype');
var link = $("#RootDirectory").val();
switch (reportType) {
//other cases
case 8: //Certification
var certId = $(this).data('certid'); //Get certid data from object
link += '/Reports/ReportPopUp.aspx?report=' + reportType + '&CertId=' + certId;
break;
}
//code
});
});
在源文件中,它响应并按预期工作。但是,如果我尝试将源代码片段从source.js移动到全局common.js(我确认该文件在执行期间被加载),它根本没有响应,并且单击链接时什么也不做:
内部常见。 js文件:common.js文件
//declaration of global variables
$(document).ready(function() {
}
$(document.body).on('click', '.printreport', function() {
//code
}
结构同上,但它不是封装成任何东西。
我的问题是:我是不是正在加载document.body部分?可能导致这种无反应的原因是什么?
您是否尝试过移动文档就绪函数中的事件侦听器? –
@AndrésAndrade我认为它是一种可能的魔药。你的意思是像移动document.ready部分中的整个document.body? –
没错。顺便说一句,在文档树顶部附近附加委托事件处理程序可能会降低性能(本例中为document.body),因为每次发生事件时,jQuery都必须将该类型的所有附加事件的所有选择器与事件目标直到文档的顶部。为获得最佳性能,请在尽可能靠近目标元素的文档位置附加委派事件。 (http://api.jquery.com/on) –