How to use jquery correctly in SharePoint Web Part - jquery doesn't always fire

自作多情 提交于 2019-12-01 06:07:21
Alex Angas

Check the rendered HTML for the ScriptLink control and see if you can browse to the location given by the <script> tag. This should give you some ideas about what's going wrong.

Also, have a look at this question which contains options for adding jQuery to SharePoint. (Disclaimer: one of the answers is mine and the method I currently use.)

Recently I have encountered with a problem I think it might help someone.

In SharePoint head tag if you place the script tag like

<script language="javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"/>

then jQuery is not working but if you place like

<script language="javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>

See the </script> difference then it's working.

I am surprised!

The main problem with JavaScript code not consistenly firing when a page is loaded is because the entire page may not have finished loading and therefore the internal DOM may not have been completely constructed yet.

The best way to fix this is to hook your code to the load or ready event.

For example

<script language="javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>

<script language="javascript">
function doSomething()
{
  // Your code goes here
}

jQuery.event.add(window, "ready", doSomething);
</script>

For detailed examples on how to use this in SharePoint, see http://www.muhimbi.com/blog/2009/07/massage-sharepoint-into-submission.html and http://www.muhimbi.com/blog/2009/07/automatically-add-search-as-you-type-to.html

I think it is a timing issue. Try this. Add the LoadAfterUI="true"

<SharePoint:ScriptLink ID="SPScriptLink" runat="server" LoadAfterUI="true" Localizable="false" Name="sp.js">
</SharePoint:ScriptLink>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!