使用javascript从服务器端的名称列表中创建按钮/href

Creating buttons/href from a list of names on the server side with javascript?

本文关键字:创建 按钮 href 列表 javascript 服务器端 使用      更新时间:2023-09-26

我有一个按钮名称和uri列表,其中包含指向我网站中其他页面的链接。这存储在我的数据库中。我还有一个javascript函数,可以在页面加载时动态创建按钮。现在,我需要的是在服务器端迭代按钮名称列表,并为列表中的每个按钮创建一个按钮?

这可能吗。我想也许可以使用字符串生成器来构建一些html来创建按钮,或者我更喜欢的方法是在每次需要新按钮时调用javascript。

这是我的javascript函数:

    function createHref(Name, Uri) {
        var leftDiv = document.createElement("div"); //Create left div
        leftDiv.id = "left"; //Assign div id
        leftDiv.setAttribute("style", "float:left; width:66.5%; line-height: 26px;       text-align:left; font-size:12pt; padding-left:8px; height:26px;"); //Set div attributes
        leftDiv.style.background = "#FF0000";
        a = document.createElement('a');
        a.href = Uri;
        a.innerHTML = Name
        leftDiv.appendChild(a);
        document.body.appendChild(leftDiv);
    }

由于这是ASP.NET,我将使用Repeater并将数据源设置为从数据库中提取的按钮数据。

为了举例说明,我假设您有一个自定义对象MyButton,它映射到您的数据:

public class MyButton
{
     public MyButton()
     {}
     public string Name { get; set; }
     public string Href { get; set; }
}

然后你会有一些中继器的标记:

<asp:Repeater ID="rptMyButtons" runat="server" OnItemDataBound="rptMyButtons_ItemDataBound">
   <HeaderTemplate>
       <ul>
   </HeaderTemplate>
       <ItemTemplate>
            <li>
               <asp:HyperLink ID="hypUrl" runat="server" />
            </li>
       </ItemTemplate>
   <FooterTemplate>
       </ul>
   </FooterTemplate>
</asp:Repeater>

然后,您将数据绑定到中继器,并在对象上设置一些属性:

 protected void Page_Load(object sender, EventArgs e)
 {
      if(!Page.IsPostBack)
      {
           rptMyButtons.DataSource = //your data from the database
           rptMyButtons.DataBind();
      }
 }
protected void rptMyButtons_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
    {
         MyButton button = (MyButton)e.Item.DataItem;
         HyperLink hypUrl = (HyperLink)e.Item.FindControl("hypUrl");
         hypUrl.Text = button.Name;
         hypUrl.NavigateUrl = button.Href;
    }
}

看起来你可能正在试图建立一个网站地图?

我有一个按钮名称和uri的列表,其中包含我的网站中其他页面的链接

这就是为什么我使用<ul><li>将您的按钮包含在更有意义的列表中。然而,很容易将其更改回<div>