简体   繁体   English

ASP.NET / JavaScript中的动态标签

[英]Dynamic labels in ASP.NET / javascript

The website I am working on needs to have dynamic labels, for example: If the webpage is listing the authors of a particular book (with more than one author) it would look like this: Author 1: Nikola Tesla [Remove] Author 2: Elon Musk [Remove] Author 3: Alan Turing [Remove] 我正在工作的网站需要具有动态标签,例如:如果该网页列出了特定书籍的作者(作者不止一个),则它的外观应如下所示: Author 1: Nikola Tesla [Remove] Author 2: Elon Musk [Remove] Author 3: Alan Turing [Remove]

(note that [Remove] in this case is a button that removes the particular person as a author.) (请注意,在这种情况下, [Remove]是一个按钮,可将特定的人删除为作者。)

My problem is this, let's say I removed Elon Musk as an author the label for Turing should now change to reflect that (would become Author 2 ). 我的问题是,假设我删除了Elon Musk作为作者,现在应该更改Turing的标签以反映这一点(将成为Author 2 )。

I've tried a couple different things using client side JavaScript (as the solution needs to work without refreshing the page or any postbacks) but I couldn't get close to a working solution myself, my logic seems to be off or limited by my lack of experiance in web dev.. I haven't done much Web Dev at all so I'm really learning as I'm going. 我已经使用客户端JavaScript尝试了几种不同的方法(因为该解决方案需要在不刷新页面或没有任何回发的情况下工作),但是我自己无法接近一个有效的解决方案,我的逻辑似乎被限制或受到了限制。 Web开发人员缺乏经验。我根本没有做太多的Web开发,因此我正在学习。 The solution would also need to work in the case of the user adding a new author to the book. 在用户向书中添加新作者的情况下,该解决方案也需要起作用。

Edit: The authors are NOT stored in a table but rather just listed using labels. 编辑:作者不是存储在表中,而是使用标签列出。 This (due to things out of my control) cannot be changed. 由于某些事情我无法控制,因此无法更改。

Edit 2: Here is the code I believe is relevant let me know if anything else is needed. 编辑2:这是我认为相关的代码,请告知我是否还有其他需要。
<div ID='dvAuthor" + i.ToString + "' class='form-group'><div class='col-sm-4 control-label'>

An added twist is that that is on the server side and it replaces a placeholder when the author is added (this means when an author is added that page does refresh -- this is fine, but removing should not require the same). 增加的一种扭曲是,它在服务器端,并且在添加作者时替换了占位符(这意味着在添加作者时页面会刷新-很好,但是删除不需要这样做)。 Even more fun is that we're not using JQuery! 更有趣的是,我们没有使用JQuery!

The i.ToString is just an integer that is added so that the author's ID is numbered, ex dvAuthor0 and so on. i.ToString只是添加的一个整数,以便对作者的ID进行编号,例如dvAuthor0 ,依此类推。

Edit 3: Reply to @Basic 编辑3:回复@Basic

Okay that clears things up a bit. 好的,这可以使事情变得清晰起来。 The div for the author's label is coming from the server (ie each time an author is added the page refreshes and the client now has the newly added author presented to them.) So I guess my question is, how would I loop through the div's on the client, or even better could I loop through each author's div and just grab their IDs if I don't know exactly how many authors are on the page? 作者标签的div来自服务器(即,每次添加作者时,页面都会刷新,并且客户端现在会向他们呈现新添加的作者。)所以我想我的问题是,我将如何遍历div在客户端上,或者甚至更好的是,如果我不确切知道页面上有多少位作者,我可以遍历每个作者的div并仅获取他们的ID? Would it be something like this while(hasNextAuthor) {add author ID to array} Sorry for all the questions, I'm really new to Web Dev stuff, I am trying my best. while(hasNextAuthor) {add author ID to array}会是这样吗?对不起,所有问题,我真的是Web开发人员的新手,我正在努力。

Also, I don't need to worry about removing the authors from the webpage, I have a function that does that already (both in the client side and on the server). 另外,我不必担心从网页上删除作者,我已经有一个功能可以做到(无论是在客户端还是在服务器上)。 The numbering is the only thing that needs to be done and it really is only cosmetic, the current numbering system works okay but does not dynamically change the numbering as the user removes authors, but rather waits until the user selects save and then reloads the page with correct numbering. 编号是唯一需要做的事情,而且实际上只是表面上的装饰,当前的编号系统可以正常工作,但是不会随着用户删除作者而动态更改编号,而是等到用户选择保存然后重新加载页面使用正确的编号。

Edit 4: I think I have a way I can get this done, I just have one hang up... How can I get the number of authors on the webpage from the client side? 编辑4:我想我有办法完成这项工作,只是挂了一个电话...如何从客户端获取网页上的作者数量? Is their a way in JavaScript where I can loop through and see how many div s are created for the webpage? 他们在JavaScript中是否可以循环浏览并查看为网页创建了多少个div

There are libraries available which do templating through JavaScript. 有可用的库通过JavaScript进行模板化。 Knockout is a good one, which you can learn more about here: http://knockoutjs.com/documentation/template-binding.html ...and see a good example here: https://www.devbridge.com/articles/knockout-a-real-world-example/ 淘汰赛是一个不错的选择,您可以在此处了解更多信息: http : //knockoutjs.com/documentation/template-binding.html ...并在此处查看一个很好的示例: https : //www.devbridge.com/articles /淘汰赛-A-真实世界的例子/

Using Knockout, you basically create a client-side ViewModel and an observable array of authors. 使用Knockout,基本上可以创建客户端ViewModel和可观察的作者数组。 They can then be bound to template HTML UI, which interacts with the ViewModel until it's time to save it back. 然后可以将它们绑定到模板HTML UI,该模板与ViewModel进行交互,直到需要将其保存回去为止。

Re-binding should be of little concern using that library. 使用该库,重新绑定应该无关紧要。

Original JQuery Solution 原始JQuery解决方案

You can use an array with odd numbered indexes and bind to it. 您可以使用具有奇数索引的数组并将其绑定。 That way you can account for missing indexes. 这样,您可以解决丢失的索引。

There is an older stackoverflow article here that answers your question. 这里有一个较旧的stackoverflow文章可以回答您的问题。

It amounts to specifying the index of each element along with the input value: 它等于指定每个元素的索引以及输入值:

<input type="hidden" name="Author.Index" value="3" />

If you are purely looking to make the text pretty you can do: 如果您只是想使文字漂亮,可以执行以下操作:

<div id="author_1" class="author-container">Author <span class="authors" data-index="1">1</span>: First Last <a ..>[Remove]</a></div>

Then in JavaScript you can do (Assuming JQuery) : 然后,您可以在JavaScript中执行(假设使用JQuery)

function UpdateIndexes()
{
   var idx = 1;
   $(".authors").each(function(el){
      $(this).text(idx);
      idx++;
   });
}

$(function(){
    $(".whateverRemoveSelector").on("click", function(){
      $(this).parents(".author-container").remove();
      UpdateIndexes();
   });
})

Just JavaScript Solution 只是JavaScript解决方案

I tried to keep the variable names vanilla enough to make this easy to follow. 我试图使变量名足够香草,以使其易于理解。 This does both creation from the author's array, wiring the remove event, as well as renumbering the author's. 这既可以根据作者的数组进行创建,也可以连接remove事件,也可以对作者的事件进行重新编号。

Hopefully this solves what you need to do! 希望这可以解决您需要做的事情!

 var authors = [ { Name: "JK Rowling" }, { Name: "Orson Scott Card" }, { Name: "Stephen King" }, { Name: "Nicholas Sparks" } ]; /* <div ID='dvAuthor" + i.ToString + "' class='form-group'><div class='col-sm-4 control-label'> */ function Remove(){ var e = event.target.parentNode.parentNode; e.parentNode.removeChild(e); var numbers = document.getElementsByClassName("sel-author-number"); for(var i = 0; i < numbers.length; i++){ var number = numbers[i]; number.innerHTML = i+1; } } window.onload = function(){ var authors = [ { Name: "JK Rowling" }, { Name: "Orson Scott Card" }, { Name: "Stephen King" }, { Name: "Nicholas Sparks" } ]; var e = document.getElementById("authorsContainer"); for(var i = 0; i < authors.length; i++){ var container = document.createElement("div"); var author = document.createElement("div"); var authorNumber = document.createElement("span"); authorNumber.setAttribute("class", "sel-author-number"); authorNumber.appendChild(document.createTextNode((i+1))); container.setAttribute("class", "form-group"); var authorID = "author" + (i+1); container.setAttribute("id", authorID); author.setAttribute("class","col-sm-4 control-label"); author.appendChild(authorNumber); author.appendChild(document.createTextNode(": " + authors[i].Name)); var removeLink = document.createElement("span"); removeLink.appendChild(document.createTextNode("[Remove]")); author.appendChild(removeLink); container.appendChild(author); e.appendChild(container); removeLink.onclick = function(){ Remove(); }; } }; 
 <div id="authorsContainer"></div> 

You've got 2 different issues; 您有2个不同的问题;

  • Manage a list of authors (possibly with ids) 管理作者列表(可能带有ID)
  • Display a numbered list 显示编号列表

For the first part, have an array or authors and use js to add/remove. 对于第一部分,有一个数组或作者,然后使用js添加/删除。 If you're not familiar with the technique, see this answer . 如果您不熟悉该技术,请参阅此答案 When any change is made to that array, call a second "update screen" function which clears the <div> holding the authors and re-creates its contents. 当对该数组进行任何更改时,调用第二个“更新屏幕”函数,该函数将清除保存作者的<div>并重新创建其内容。

Your update() function might look something like this: 您的update()函数可能看起来像这样:

//Add and remove from authors as you wish, then call update()
var authors = ['Bob', 'Sue'];

function update() {
    var container = document.getElementById('Authors');

    //clear the container, open a list
    container.innerHTML = "<ul>"

    //Recreate the contents...
    for(var i = 0; i < authors.length; i++) {
        //Add the author
        container.innerHtml += '<li>' + i + '. ' + authors[i] + '</li>';
    }

    //Close the list
    container.innerHTML += "</ul>"
}

Of course, if you're using jQuery this code can be cleaned up considerably... 当然,如果您使用的是jQuery,则此代码可以被大量清理...

Edit: It doesn't matter where the authors are coming from originally, you can get them into a javascript list easily. 编辑:最初来自哪里的作者都无所谓,您可以轻松地将他们放入javascript列表。 Guessing a bit at what the looping code/object model looks like, change your code that generates the divs 猜测一下循环代码/对象模型的样子,更改生成div的代码

<% For i = ... %>
    <div ID='dvAuthor" + i.ToString + "' class='form-group'><div class='col-sm-4 control-label'>
<% Next %>

to generate array entries instead 生成数组条目

var authors = [];
<% for i = ... %>
    authors[i] = '<%=Authors(i).Name.Replace("'", "\'") %>';
<% Next %>

or if that's not possible, you can populate the list from the current page contents (messier but...) 或者,如果您无法执行此操作,则可以从当前页面的内容中填充列表(麻烦但...)

var authors = [];
var authorDivs = document.getElementById("Container").getElementsByTagName("div");
for(var i=0;i<authorDivs.length;i++) {
    authors[i] = authorDivs[i].innerHTML;
}

And with nothing extraneous: 而且没有多余的东西:

var authorDivs = document.getElementById("Container").getElementsByTagName("div");
for(var i=0;i<authorDivs.length;i++) {
    var currentId = authorDivs[i].id;
    var currentContents = authorDivs[i].innerHTML;
    // etc...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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