如何将 JQuery 与母版页一起使用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/292787/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use JQuery with Master Pages?
提问by Keith Myers
I can get simple examples to work fine as long as there's no master page involved. All I want to do is click a button and have it say "hello world" with the javascript in a .js file, using a master page. Any help very much appreciated :)
只要不涉及母版页,我就可以让简单的示例正常工作。我想要做的就是单击一个按钮,并使用母版页在 .js 文件中使用 javascript 说“hello world”。非常感谢任何帮助:)
采纳答案by tvanfosson
EDIT
编辑
As @Adam points out in the comments, there is a native jQuery mechanism that basically does the same thing as the hack in my original answer. Using jQuery you can do
正如@Adam 在评论中指出的那样,有一个原生的 jQuery 机制,它基本上与我原始答案中的 hack 做同样的事情。使用 jQuery 你可以做到
$('[id$=myButton]').click(function(){ alert('button clicked'); });
My hack was originally developed as a Prototype work around for ASP.NET and I adapted it for the original answer. Note that jQuery basically does the same thing under the hood. I recommend using the jQuery way, though, over implementing my hack.
我的 hack 最初是作为 ASP.NET 的原型工作而开发的,我将其改编为原始答案。请注意,jQuery 基本上在幕后做同样的事情。不过,我建议使用 jQuery 方式,而不是实现我的 hack。
Original answer left for comment context
原始答案留给评论上下文
When you use a master page, ASP.NET mangles the names of the controls on the dependent pages. You'll need to figure out a way to find the right control to add the handler to (assuming you're adding the handler with javascript).
当您使用母版页时,ASP.NET 会修改相关页上控件的名称。您需要找到一种方法来找到正确的控件来添加处理程序(假设您使用 javascript 添加处理程序)。
I use this function to do that:
我使用这个函数来做到这一点:
function asp$( id, tagName ) {
var idRegexp = new RegExp( id + '$', 'i' );
var tags = new Array();
if (tagName) {
tags = document.getElementsByTagName( tagName );
}
else {
tags = document.getElementsByName( id );
}
var control = null;
for (var i = 0; i < tags.length; ++i) {
var ctl = tags[i];
if (idRegexp.test(ctl.id)) {
control = ctl;
break;
}
}
if (control) {
return $(control.id);
}
else {
return null;
}
}
Then you can do something like:
然后你可以做这样的事情:
jQuery(asp$('myButton','input')).click ( function() { alert('button clicked'); } );
where you have the following on your child page
您的孩子页面上有以下内容
<asp:Button ID="myButton" runat="server" Text="Click Me" />
回答by djuth
If your site has content pages in other folders, using the Page's ResolveUrl
method in the src path will ensure that your js file can always be found:
如果您的站点在其他文件夹中有内容页面,则ResolveUrl
在 src 路径中使用 Page 的方法将确保始终可以找到您的 js 文件:
<script type="text/javascript" src='<%= ResolveUrl("~/Scripts/jquery-1.2.6.min.js") %>' ></script>
回答by Adam Lassek
Make sure that jQuery is being added in the master page. Given that you have this control:
确保在母版页中添加了 jQuery。鉴于您有此控制权:
<asp:Button ID="myButton" runat="server" Text="Submit" />
You can wireup the javascript with this:
您可以使用以下方法连接 javascript:
$(document).ready(function() {
$('[id$=myButton]').click(function() { alert('button clicked'); });
});
$(document).ready()
fires when the DOM is fully loaded, and all the elements should be there. You can simplify this further with
$(document).ready()
当 DOM 完全加载时触发,并且所有元素都应该在那里。您可以进一步简化
$(function() {});
The selector syntax $('[id$=myButton]')
searches elements based on their id attribute, but matches only the end of the string. Conversely, '[id^=myButton]'
would match the beginning, but for the purposes of filtering out the UniqueID that wouldn't be very useful. There are many many more useful selectors you can use with jQuery. Learn them all, and a lot of your work will be done for you.
选择器语法$('[id$=myButton]')
根据元素的 id 属性搜索元素,但只匹配字符串的结尾。相反,'[id^=myButton]'
将匹配开头,但为了过滤掉不太有用的 UniqueID。您可以在 jQuery 中使用更多有用的选择器。全部学习它们,你的很多工作都会为你完成。
The problem is that ASP.Net creates a unique id and name attribute for each element, which makes finding them difficult. It used to be that you'd need to pass the UniqueID property to the javascript from the server, but jQuery makes that unneccessary.
问题在于 ASP.Net 为每个元素创建了唯一的 id 和 name 属性,这使得查找它们变得困难。过去,您需要将 UniqueID 属性从服务器传递给 javascript,但 jQuery 使这变得不必要。
With the power of jQuery's selectors, you can decouple the javascript from the server-side altogether, and wireup events directly in your javascript code. You shouldn't have to add javascript into the markup anymore, which helps readability and makes refactoring much easier.
借助 jQuery 选择器的强大功能,您可以将 javascript 与服务器端完全分离,并直接在您的 javascript 代码中连接事件。您不应该再将 javascript 添加到标记中,这有助于提高可读性并使重构更容易。
回答by gius
Just move the <script type="text/javascript" src="jquery.js" />
tag into the head tag in the master page. Then you can use jquery in all content pages.
只需将<script type="text/javascript" src="jquery.js" />
标记移动到母版页中的 head 标记中即可。然后您可以在所有内容页面中使用 jquery。
There is no magic about using master pages with jQuery.
在 jQuery 中使用母版页没有什么神奇之处。
回答by AFD
Adam's solution is the best. Simple!
亚当的解决方案是最好的。简单的!
Master page:
母版页:
<head runat="server">
<title></title>
<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
<asp:ContentPlaceHolder ID="HeadContent" runat="server">
</asp:ContentPlaceHolder>
</head>
Content page:
内容页:
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script type="text/javascript">
$(document).ready(function () {
$("[id$=AlertButton]").click(function () {
alert("Welcome jQuery !");
});
});
</script>
</asp:Content>
where the button is
按钮在哪里
<asp:Button ID="AlertButton" runat="server" Text="Button" />
回答by Jared
Reference the the Jquery .js file in the head of the MasterPage as follows:
引用MasterPage头部的Jquery .js文件如下:
<script type="text/javascript" src="/Scripts/jquery-1.2.6.min.js"></script>
(some browsers don't like ending it with />)
(有些浏览器不喜欢以 /> 结尾)
Then you can write things like
然后你可以写这样的东西
$('#<%= myBtn.ClientID%>').show()
in your javascript making sure to use the ClientId when referencing an ASP.Net control in your client code. That will handle any "mangling" of names and ids of the controls.
在您的 javascript 中,确保在您的客户端代码中引用 ASP.Net 控件时使用 ClientId。这将处理控件的名称和 ID 的任何“修改”。
回答by Nitin Nayyar
When pages are rendered along with master pages, control id gets changed on page rendering so we can't refer them in jQuery like this #controlid
. Instead we should try using input[id$=controlid]
. If control is rendered as input control or if as anchor tag use a[id$=controlid]
in jQuery.
当页面与母版页一起呈现时,控件 id 在页面呈现时会发生变化,因此我们不能像这样在 jQuery 中引用它们#controlid
。相反,我们应该尝试使用input[id$=controlid]
. 如果控件呈现为输入控件或作为锚标记a[id$=controlid]
在 jQuery 中使用。
回答by hoodwink
In case if some one wants to access a label, here is the syntax
如果有人想要访问标签,这里是语法
$('[id$=lbl]').text('Hello');
where lbl
is the label id and the text to display in the label is 'Hello'
lbl
标签 id在哪里,标签中显示的文本是“你好”
回答by Patrick de Kleijn
Master page:
母版页:
The jQuery library goes in the master page. See if the path is correctly referenced. You might like to add the extra documentation like this:
jQuery 库位于母版页中。查看是否正确引用了路径。您可能想添加这样的额外文档:
<head>
<script type="text/javascript" src="/Scripts/jquery-1.2.6.min.js"></script>
<% if (false) { %>
<script type="text/javascript" src="/Scripts/jquery-1.2.6-vsdoc.js"></script>
<% } %>
</head>
Master page:
母版页:
<head>
<script type="text/javascript">
$(document).ready(
function()
{
alert('Hello!');
}
);
</script>
</head>
CodeBehind for content pages and user controls:
内容页面和用户控件的代码隐藏:
this.textBox.Attributes.Add("onChange",
String.Format("passElementReferenceToJavascript({0})", this.textBox.ClientID));
回答by Stefan
Check out this post:
看看这个帖子:
http://blogs.msdn.com/webdevtools/archive/2008/10/28/rich-intellisense-for-jquery.aspx
http://blogs.msdn.com/webdevtools/archive/2008/10/28/rich-intellisense-for-jquery.aspx
also explains how to get intellisense for jQuery in Visual studio.
还解释了如何在 Visual Studio 中为 jQuery 获取智能感知。