2014-02-11 37 views
0

我有一个滚动到锚功能:需要注册代码javascript函数后面再调用它

function scrollToAnchor(aid) { 
    var aTag = $("a[name='" + aid + "']"); 
    if (aTag.length) { 
     $('html,body').animate({ 
      scrollTop: aTag.offset().top - 100 
     }, 'slow'); 
     aTag.closest('.subpanel').effect("highlight", 5000); 
    } 
} 

HTML

<a id="A2" class="gridLabel" name="Add Action Item"> 
    <span id="MainContent_Label19" title="Add/Edit an action item.">Add/Edit Action Item</span> 
</a> 

我要调用服务器端事件执行某种行动。一旦行动完成,我需要调用这个scrollToAnchor。我尝试这样做:

ScriptManager.RegisterClientScriptBlock(this, GetType(), "OpenActions", "$(function(){ 
function scrollToAnchor(aid) { var aTag = $('a[name=''' + aid + ''']');if (aTag.length) 
{$('html,body').animate({ scrollTop: aTag.offset().top - 100 }, 
'slow');aTag.closest('.subpanel').effect('highlight', 5000);}} $('#tblAction').show(); 
scrollToAnchor('Add Action Item');});", true); 

但是我得到的console' '" ",可能是因为错误。有人可以帮助我形成这个。

我也试过:

ScriptManager.RegisterClientScriptBlock(this, GetType(), "OpenActions", "$(function() 
{function scrollToAnchor(aid) { var aTag = $('a[name=\"' + aid + '\"]' + ']');if 
(aTag.length) {$('html,body').animate({ scrollTop: aTag.offset().top - 100 }, 
'slow');aTag.closest('.subpanel').effect('highlight', 5000);}} $('#tblAction').show(); 
scrollToAnchor('Add Action Item');});", true); 
+1

小心从你的控制台分享错误? – Xotic750

回答

1

这个问题似乎是在这里:

'a[name=''' + aid + ''']' 

尝试更换与:

'a[name=' + aid + ']' 

或者,如果你的价值需要报价名称:

'a[name=\'' + aid + '\']' 
// Or 
'a[name=\"' + aid + '\"]' 
+0

这几乎是工作,但这里是我得到的错误:未捕获的错误:语法错误,无法识别的表达式:a [name = Add Action Item]] – JonH

+0

@JonH:那么你需要使用最后2个例子之一。 – Cerbrus

+0

现在我正在获取未捕获SyntaxError:您发布第三个示例的第一个示例的意外字符串。这里是我的代码:'ScriptManager.RegisterClientScriptBlock(this,GetType(),“OpenActions”,“$(function(){function scrollToAnchor(aid){var aTag = $('a [name =''+ aid +' ')'+']'); if(aTag.length){$('html,body')。animate({scrollTop:aTag.offset()。top - 100},'slow'); aTag.closest ('.subpanel')。effect('highlight',5000);}} $('#tblAction')。show(); scrollToAnchor('Add Action Item');});“,true);' – JonH

-1

前缀你的字符串与@,像这样

ScriptManager.RegisterClientScriptBlock(this, GetType(), "OpenActions", @"$(function(){ 
function scrollToAnchor(aid) { var aTag = $('a[name=' + aid + ']');if (aTag.length) 
{$('html,body').animate({ scrollTop: aTag.offset().top - 100 }, 
'slow');aTag.closest('.subpanel').effect('highlight', 5000);}} $('#tblAction').show(); 
scrollToAnchor('Add Action Item');});", true); 
1

我会做的就是把功能在页面上(或在页面加载的js文件),然后简单地注册像这样的脚本:

ScriptManager.RegisterClientScriptBlock(this, GetType(), 
"OpenActions", "scrollToAnchor('Add Action Item');", true); 

从我可以告诉你,你不需要注册每个服务器端事件的整个脚本。你只需要用给定的参数运行该函数。

相关问题