点击任何剧透总是首先打开



我在asp-net上有一个新闻博客。 新闻有剧透。页面上有一些有剧透的新闻。但是,如果我点击任何剧透(第一个、第二个、第三个(,那么无论如何都只会打开第一个。我知道这是因为所有按钮和字段都具有相同的id。如何实现按钮与扰流板的连接?点击特定剧透后必须打开,但不是第一个。


<div>
<label>Body</label>
<button type="button" id="button">Add spoiler</button>
<textarea id="spoilerField" asp-for="Body"></textarea>
</div>
@section scripts {
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
var textarea = document.getElementById("spoilerField");
var button = document.getElementById("button");
button.onclick = function () {
var len = textarea.value.length,
start = textarea.selectionStart,
end = textarea.selectionEnd,
sel = textarea.value.substring(start, end),
replace = '<input type="checkbox" id="spoiler2"/><label for="spoiler2">SEE SPOILER</label><div class="spoiler">' + sel + '</div>';
textarea.value = textarea.value.substring(0, start) + replace + textarea.value.substring(end, len);
}
</script>
}

无论如何,您仍然应该使这些 id 唯一,例如,您可以使用带有 Razor 和索引的 for 循环将元素添加到页面并连接 2。

然后,id 将如下所示:

id="spoiler_@i"

除此之外,您应该查看querySelectorAll或getElementsByClassName来选择这些元素并执行您需要执行的操作。

最新更新