使用JQuery/Typescript和KnockoutJS禁用for循环中的textarea &g



所以我有一个for循环,它将显示一个文本区域列表。每个都有一个使用KO数据绑定属性的唯一id,但是它们都有相同的名称。我想做的是使用Jquery来检查列表中的所有文本区域是否为空,在这种情况下,它将禁用除第一个文本区域之外的每个文本区域,或者如果其中一个文本区域被填充,具有空字符串值的文本区域将被禁用。目前,我的代码看起来像这样:

打印稿/Jquery

thisMethod(): any {
this.check.subscribe(val => {
if (val === true) {
$("textarea[name='text']").each((i, element) => {
if ($(element).val() === "") {
if (i !== 0) {
$(element).prop('disabled', true);
};
}
else {
// some check for populated textbox to disable unpopulated checkboxes
}
}
}
}
}

HTML

<div data-bind="foreach: choice">
<-- ko if: hasData($data) -->
<div>
<textarea class="form-control" name="text" data-bind="attr: {id: $data + '-choice-text'}, event: {change: $root.anonClass.thisMethod}"></textarea>
</div>
</div>

我认为我的困惑主要源于不理解jquery。使用.each(),在移动到下一个条件之前,它是否首先验证每个元素,还是像普通的for循环一样迭代?

在测试第一个if块时,似乎没有发生任何事情。这可能与Jquery完全无关,可能是knockout change事件未触发的结果,但我不确定。

.each()只是循环遍历整个集合。您是否尝试控制台记录.each()中的所有元素以检查它们是否被正确选择?

你的代码几乎工作,但它总是使第一个是启用的,即使另一个有值。

我可能会这样做,因为在我看来这更清楚一些:

  • 查找所有空文本区并禁用
  • 如果所有文本区都是空的,只重新启用第一个

$('#check').click(() => {
const $areas = $('textarea');

/*
// your code does work, but leaves the first one enabled, even if another one has a value
$areas.each((i, element) => {
if ($(element).val() === "") {
if (i !== 0) {
$(element).prop('disabled', true);
};
}
else {
// some check for populated textbox to disable unpopulated checkboxes
}
});
*/


const $emptyAreas = $areas.filter((i,t) => !t.value);
$emptyAreas.prop('disabled', true);

if ($emptyAreas.length === $areas.length) {
// all empty
$areas.first().prop('disabled', false);
}
});
$('#reset').click(() => $('textarea').prop('disabled', false).val(''));
textarea {
display:block;
margin-bottom:1rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea></textarea>
<textarea></textarea>
<textarea></textarea>
<textarea></textarea>
<button id="check">check</button>
<button id="reset">reset</button>

最新更新