[英]Razor View find Id assigned in loop from javascript
我有以下內容:
for (int i = 0; i < Model.Questions.Count; i++)
{
@Html.TextAreaFor(modelItem => Model.Questions[i].AnswerText, new { @class = "form-control multi", rows = "6" })
<div class="remaining-counter">
<p><span id="Counter_@i"></span> characters remaining</p>
</div>
}
我試圖使用jquery簡單地計算每個文本區域的剩余計數器
$('.multi').simplyCountable({
counter: 'How to get the id here',
countType: 'characters',
maxCount: 4000,
strictMax: false,
countDirection: 'down',
thousandSeparator: ',',
});
我不知道的是如何獲得計數器跨度的相應id,顯示剩余計數<span id="Counter_@i"></span>
我不知道它是否正確,但你可以在jquery.simplyCountable.js文件中替換這一行: -
var counter = $(options.counter);
with
var counter = $(this).next().find('span');
或者你可以這樣做: -
$(function () {
$('.multi').each(function () {
var id = $(this).next().find('span').attr('id');
$(this).simplyCountable({
counter: '#' + id,
countType: 'characters',
maxCount: 4000,
strictMax: false,
countDirection: 'down',
thousandSeparator: ',',
});
});
});
對不起,但我覺得黑客插件硬連線選擇器是一個可怕的解決方案。
選項1 - 無需更改插件
JSFiddle: http : //jsfiddle.net/TrueBlueAussie/e82kf82r/7/
您可以迭代.multi
元素並使用匹配的span ID單獨連接它們,如下所示:
$(function () {
$('.multi').each(function () {
var counter = $(this);
counter.simplyCountable({
counter: '#' + counter.next().find("span").attr('id'),
countType: 'characters',
maxCount: 4000,
strictMax: false,
countDirection: 'down',
thousandSeparator: ',',
});
});
});
選項2 - 改進插件
一個更好的解決方案是改進插件,以便使用counter
選項查找相對於插入元素的元素。這將需要一個共同的祖先元素,以便可以找到textarea
和counter。
JSFiddle: http : //jsfiddle.net/TrueBlueAussie/e82kf82r/9/
$(function () {
$('.container').simplyCountable({
counter: 'span',
countType: 'characters',
maxCount: 4000,
strictMax: false,
countDirection: 'down',
thousandSeparator: ',',
});
});
HTML更改(添加父div):
<div class="container">
<textarea class="multi"></textarea>
<div class="remaining-counter">
<p><span class="safe">3,979</span> characters remaining</p>
</div>
</div>
插件更改摘錄:
默認選項添加text
選擇器:
$.fn.simplyCountable = function (options) {
options = $.extend({
text: 'textarea',
counter: '.counter',
新的插件初始化代碼如下所示:
return $(this).each(function () {
var $element = $(this);
var countable = $element.find(options.text);
var counter = $element.find(options.counter);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.