简体   繁体   中英

Call javascript function in for loop code-behind

I have a js function that creates nav-tabs dynamically like this:

    function newTab(i) {

         for (var x = 0; x<i; x++ ){
             var nextTab = $('#tabs li').size() + 1;

             // create the tab
             $('<li><a href="#tab' + nextTab + '" data-toggle="tab">Tab ' + nextTab + '</a></li>').appendTo('#tabs');

             // create the tab content
             $('<div class="tab-pane" id="tab' + nextTab + '">tab' + nextTab + ' content</div>').appendTo('.tab-content');
         }
     };

I send the i parameter from my code behind

 Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    Dim dtAreas As New DataTable
    Dim i As Integer 

    dtAreas = EvaRH.GetAreas
    i = dtAreas.Rows.Count - 1

    ClientScript.RegisterStartupScript(Page.GetType(), "Tab1", "newTab('" & i & "')", True)

End Sub

This is working fine, however I would like to set the tabs names to the ones I have on my Areas dataset, so first I changed my JS function to this:

function newTab() {

         var nextTab = $('#tabs li').size() + 1;

         // create the tab
         $('<li><a href="#tab' + nextTab + '" data-toggle="tab">Tab ' + nextTab + '</a></li>').appendTo('#tabs');

         // create the tab content
         $('<div class="tab-pane" id="tab' + nextTab + '">tab' + nextTab + ' content</div>').appendTo('.tab-content');
 };

And tried to create the tabs calling this function multiple times on a for loop from code behind:

    For i = 0 To dtAreas.Rows.Count - 1
        ClientScript.RegisterStartupScript(Me.GetType(), "tab" & i.ToString, "newrTab()", True)
    Next

But its not working, doesnt gives me any errors neither creates any tabs. I have tried setting the js key value static, but didnt worked, also tried this two:

Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "tab" & i.ToString, "newTab()", True)
ScriptManager.RegisterStartupScript(Page, Me.GetType(), "tab" & i.ToString, "newTab()", True)

I have also tried replacing the & with + with no succes

Client scripts and server code cannot be mixed this way. Javascript only runs on the browser and the only way it can communicate with your backend script is via AJAX (or some other network) calls.

Instead, have your server render out the HTML for the tabs with the names, as well as the tab panes with their respective content, then have your script find those tabs (based on the data attributes) and turn them into dynamic navigation. This will be better for SEO since even if javascript is disabled, your site content is still visible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM