SharePoint 2010 关于Jquery的10个小技巧

10 jQuery snippets for SharePoint 2010

                                         

I like to collect pieces of code snippets, sooner or later I’ll found them useful and they could save time and other efforts. My intention with this post is just to share a couple of my snippets and I hope that you’ll found something useful here.

Maybe you see something that can be written more efficient or if you have some cool snippets of your own you like to share, please drop this in a comment. These snippets are all plugin independent and should be easy to follow and modify and they can be used in SharePoint Designer 2010, Visual Studio or be included in a text file in SharePoint linked from a content editor. Don’t forget to create a reference to latest jQuery in the master page or into the text file.

1. Text manipulation
In this example I replace ‘All site content’ with help of the each function.

1 /* --- Doc ready ---*/
2 $(document).ready(function() {
3 $('.ms-splinkbutton-text').each(function(i){ $(this).text($(this).text().replace('All Site Content','More stuff here..'))
4 })

2. Check the URL
If the URL contains ‘news’, let’s do something conditionally with JS.

1 if(document.URL.indexOf("news") != -1){
2 alert("News site");
3 } else{
4 alert("Not the news site");
5 }

Another way is to getting a URL parameter and maybe their values and to something based on a condition with help of jQuery. Let’s give the background different colors depending if the view are sorted by Desc or Asc

01 var url = window.location.href;
02 /* --- Doc ready ---*/
03 $(document).ready(function() {
04 if (url.search("&SortDir=Asc") > 0) {
05 $(".ms-viewheadertr").css('background-color','lime');
06 };
07 else if (url.search("&SortDir=Desc") > 0) {
08 $(".ms-viewheadertr").css('background-color','yellow');
09 };
10 /* --- End doc ready ---*/
11 });

3. Timestamp
If each page you create needs to have a unique name, you can set a time stamp when it creates. In this example I’ve used year to milliseconds and a random number at the end. This may be useful for a news site with many pages.

01 // create a timestamp with random
02 var now = new Date();
03 var year = now.getFullYear();
04 var month = now.getMonth();
05 var day = now.getDay();
06 var hours = now.getHours();
07 var minutes = now.getMinutes();
08 var seconds = now.getSeconds();
09 var milliseconds = now.getMilliseconds();
10 var rand = Math.floor((Math.random()*1000000)+1);
11 var pageID = ('ID-')
12 var CustomInput = pageID + '' + year + '' + month + '' + day +'' + hours + '' + minutes + '' + seconds + '' + milliseconds +'' + rand;
13  
14 /* --- Doc ready ---*/
15 $(document).ready(function() {
16 $("input[name='ctl00$PlaceHolderMain$nameInput']").val(CustomInput);
17 /* --- End doc ready ---*/
18 });

If you only want this function for let’s say a news site, you can use an If statement and identify the URL. But don’t forget that URL can be changed.

1 /* --- Doc ready ---*/
2 $(document).ready(function() {
3 if(document.URL.indexOf("news") != -1) {
4 // Unique page title
5 $("input[name='ctl00$PlaceHolderMain$nameInput']").val(CustomInput);
6 } else{}
7 /* --- End doc ready ---*/
8 });

4. Change the attribute
Let’s say you want to change for example the title tag for the ‘I Like It’ button, you can do like this to set a custom attribute.

1 /* --- Doc ready ---*/
2 $(document).ready(function() {
3 $(".ms-socialNotif-Container > a").attr({
4 title: "Click the button if you like this page",
5 });
6 /* --- End doc ready ---*/
7 });

5. Change CSS
Let’s change the header text to red if the name is Link.

1 /* --- Doc ready ---*/
2 $(document).ready(function() {
3 $(".ms-WPTitle span:contains('Links')").css("color""red");
4 });

Another way is to use a condition and a variable for this, if the web part header is equal to Shared Documents set the color to green, if the text is eq to Link set a border around the web part and set the text to red color. Normally I set the CSS into a CSS file, and you can use addClass to set the class as an option to set the CSS inline the script if you like.

01 /* --- Doc ready ---*/
02 $(document).ready(function() {
03 var WPtitle = $('.ms-WPTitle span');
04 for (var i = 0; i <= WPtitle.length; i++) {
05 if ($(WPtitle[i]).text() == 'Links') {
06 $(WPtitle[i]).css({'color''red'});
07 $(WPtitle[i]).parents().eq(10).css({'border''1px black solid!important'});
08 }
09 else if ($(WPtitle[i]).text() == 'Shared Documents') {
10 $(WPtitle[i]).css({'color''green'});
11 }}
12 /* --- End doc ready ---*/
13 });

6. Add expand / collapse web parts
The following code will get expand/collapse for all standard web parts.

01 /* --- Doc ready ---*/
02 $(document).ready(function() {
03 $(function($) {
04 $('.s4-wpTopTable').find('tr:first h3').append('<a class=\'min\' style=\'float:left; margin-right:5px\'><img src=\'/_layouts/images/collapse.gif\'/></a>');
05 var Collapse = "/_layouts/images/collapse.gif";
06 var Expand = "/_layouts/images/expand.gif";
07 $('.min').click(function(){     
08 var img = $(this).children();
09 $(this).closest('.s4-wpTopTable').find('tr:first').next().toggle().is(":visible") ? img.attr('src',Collapse) : img.attr('src',Expand );
10 });
11 });
12 });

7. Modify form field
jQuery can be used in many ways for standard list forms in SharePoint and this fist example shows how to set read only, a color and a specific width for the title field in edit mode.

1 /* --- Doc ready ---*/
2 $(document).ready(function() {
3 $("input[title='Title']").attr("readonly","true").css('background-color','#ccc').width(70);
4 /* --- End doc ready ---*/
5 });

Next example shows how to set a field limit and add a counter that shows number of characters left

01 // Show Nr of Characters left in a common list field
02 (function($){ 
03 $.fn.fieldLimit = function(options) { 
04 return this.each(function() { 
05 var characters = 30;
06 $(this).keyup(function(){
07 if($(this).val().length > characters){
08 $(this).val($(this).val().substr(0, characters));
09 }  
10 var remaining = characters - $(this).val().length;
11 $(options.result).html(remaining + " characters left");        
12 });
13 }); 
14 }; 
15 })(jQuery);
16  
17 /* --- Doc ready ---*/
18 $(document).ready(function() {
19 $('.ms-formtable').prepend("<div class='CharactersLeft'></div>");
20 $('input[title$=Title]').fieldLimit({
21 result:".CharactersLeft",
22 });
23 /* --- End doc ready ---*/
24 });

8. Check site template
If you need to do something based on which site template a site has been created from, you can identify this with help of the site template ID. I have only covered a few templates below.

01 /* --- Doc ready ---*/
02 $(document).ready(function(){
03 CurrentTemplate = g_wsaSiteTemplateId;
04 TeamSite = 'STS#0'
05 EnterpriseWiki = 'ENTERWIKI#0';
06 PublishingSite = 'CMSPUBLISHING#0';
07 if (CurrentTemplate == TeamSite){
08 alert('Im a Team site');}
09 else if (CurrentTemplate == EnterpriseWiki){
10 alert('Im a Enterprise Wiki');}
11 else if (CurrentTemplate == PublishingSite){
12 alert('Im a Publishing Site');}
13 else {
14 alert('Sitetemplate not defined yet..');}
15 /* --- End doc ready ---*/
16 });

9. Welcome message
This example shows how to work with variables. You’ll also find some plain old good JS date stuff that can be useful when you need to check times.

01 /* --- Doc ready ---*/
02 $(document).ready(function(){
03 var WelcomeMenuContent = $('.ms-welcomeMenu > a.ms-menu-a > span');
04 var UserName = WelcomeMenuContent.text();
05 var FirstName = UserName.split(" ")[0];
06 var Display;
07 var Digital = new Date()
08 var Hours = Digital.getHours()
09 Morning = 'Good morning' " " + FirstName;
10 Lunch = 'Lunch time' " " + FirstName;
11 Evening = 'Good evening' " " + FirstName;
12 Night = 'Time to go home' " " + FirstName;
13 TimeElse = 'Welcome' " " + FirstName;
14 if (Hours >= 5 && Hours <= 11)
15 WelcomeMenuContent.text(Morning);
16 else if (Hours == 12)
17 WelcomeMenuContent.text(Lunch);
18 else if (Hours >= 13 && Hours <= 17)
19 WelcomeMenuContent.text(Evening);
20 else if (Hours >= 18 && Hours <= 23)
21 WelcomeMenuContent.text(Night);
22 else
23 WelcomeMenuContent.text(TimeElse); 
24 /* --- End doc ready ---*/
25 });

10. Append today’s date
While we’re talking about get date with JS, let’s see how you can use this to display current date somewhere at the page like this.

1 var d = new Date();
2 var month = d.getMonth();
3 var date = d.getDate();
4 var year = d.getFullYear();
5 /* --- Doc ready ---*/
6 $(document).ready(function() {
7 $('.s4-pagedescription').append("<div style='float:right'>" + month + "/" + date + "/" + year + "</div>");
8 });

Stay in tune!

原文地址: http://chrisstahl.wordpress.com/2012/09/27/10-jquery-snippets-for-sharepoint-2010/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值