2014-02-11 33 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); 

從我可以告訴你,你不需要註冊每個服務器端事件的整個腳本。你只需要用給定的參數運行該函數。

相關問題