首页 > 解决方案 > 如何查找输入类型文本的 id,如果不存在则将其添加到 c-#

问题描述

如何找到 <input type= text> 的 id,如果不存在则将其添加到 C#

我已经考虑了上面的链接作为我的解决方案,但我的问题有点不同。假设将来我在第一个文本框(id=“Answer1”)之前的字符串中添加了一个新的文本框(id=“Answer4”),例如:

string Question="<input data-size="0" data-type="0" id="Answer4" placeholder="Answer4" type="text" /> 
<br/>
<br/>
<input data-size="0" data-type="0" id="Answer1" placeholder="Answer1" type="text" /> 
<br/>
<br/>
<input data-size="0" data-type="0" placeholder="Answer2" type="text" /><br/>
<br/>
<input data-size="0" data-type="0" id="Answer3" placeholder="Answer3" type="text" /><br/>
<br/>
&nbsp;";

第二个文本框中缺少 id 。我怎样才能添加它的ID。我已经完成了如下代码:

string textboxTagPattern= @"(<input)([^>]*)(type=\"")(text)(\"")([^>]*)(/>)";
Regex rgx = new Regex(textboxTagPattern, RegexOptions.IgnoreCase);
MatchCollection questionInputText = rgx.Matches(Question);

var arr = Question.Replace("<input", "^<input").Split('^');
        string ques = "";
        int count = 0;
        for (int i = 0; i < arr.Length; i++)
        {
            //If it is of <input type="text"> format and the id is not present
            if (arr[i].IndexOf("type=\"text\"") != -1)
            {
                count++;
                if (arr[i].IndexOf("id") == -1)
                {
                    arr[i] = arr[i].Insert(arr[i].IndexOf("input ") + "input ".Length, "id=\"Answer" 
                            + count + "\" ");
                     // According to this logic the 2nd and 3rd textboxes will have the same 
                      //id(id=Answer3), which is wrong. How can I correct it?
                }

            }
            ques = ques + arr[i].Replace("\n", "");
        }

标签: c#jquerylogic

解决方案


推荐阅读