我目前正在 meteor 中设计用户界面具有多个文本输入,其内容在更改时保存到 session 变量(keyup
事件)。由于 preserve-inputs
包的存在,这些输入框在聚焦时不会重新渲染。
我现在尝试默认禁用这些输入框并使其在双击时可编辑(这可能是一个糟糕的选择,但对于当前的问题来说这是最简单的,对于初稿来说已经足够了 - 也许我'稍后会在 UX 询问)。但是,当最初禁用时,输入框不会在输入单个字符时保留并重新呈现,从而再次禁用它。
虽然保留不可编辑元素不被重新渲染通常没有意义,但我在代码中找不到任何会歧视 disabled
状态的内容。那么它在哪里,我该如何规避呢? (当然,我可以在双击/模糊时设置一个 disabled
session 变量,并在启用状态下重新渲染输入框,但这对我来说似乎过于复杂)。
以下代码(请注意,它纯粹是客户端 JavaScript)重现了此问题。它还呈现第二个输入框,该输入框永远不会被禁用,但也只能在双击后才能访问。这按预期工作,无需重新渲染。现场演示已部署到 http://preserve-disabled-inputs.meteor.com/ .
disabled.html
:
<head>
<title>disabled</title>
</head>
<body>
{{> body}}
</body>
<template name="body">
<p>Double-click to enter text</p>
{{> input f}}
{{> input t}}
</template>
<template name="input">
<div style="position: relative; width: 400px;">
<input id="{{id}}" class="input" type="text" value="{{value}}" style="width: 100%;" {{disabled}}/>
<!-- events on disabled inputs are not triggered -->
<!-- overlay with transparent div to catch clicks -->
<div class="catch" style="position: absolute; left: 0; top: 0; right: 0; bottom: 0;" />
</div>
</template>
disabled.js
:
if (Meteor.isClient) {
// Setup for the example
Session.setDefault('valuefalse', 'This one is preserved and can be edited without problems');
Session.setDefault('valuetrue', 'This one is not preserved and loses focus on edit');
Template.body.t = function() {
return { disabled: true };
}
Template.body.f = function() {
return { disabled: false };
}
Template.input.disabled = function() {
return this.disabled ? 'disabled="disabled" ' : '';
}
Template.input.id = function() {
return this.disabled ? 'd' : 'e';
}
Template.input.value = function() {
return Session.get('value' + this.disabled);
}
// Here goes ...
Template.input.events({
'dblclick div.catch': function (evt) {
var input = $('input.input', evt.target.parentNode);
// Enable text box
input.removeAttr('disabled');
input.focus();
// Don't render the div so the input box becomes accessible
evt.target.style.display = 'none';
},
'keyup input.input': function (evt) {
Session.set('value' + this.disabled, evt.target.value);
},
'blur input.input': function(evt) {
// Re-render the catcher div
$('div.catch', evt.target.parentNode).css('display', '');
// Disable text box, if appliccable
if (this.disabled) evt.target.disabled = 'disabled';
}
});
}
最佳答案
对我来说,唯一有效的选择是定义disabled =“true”,因此代码如下所示:
disabled="{{#if isDisabled}}true{{/if}}"
如果 isDisabled 为 false,Meteor 甚至不会在 DOM 中渲染/显示禁用的标签(例如,disabled="")。
关于javascript - 保留 meteor 中禁用的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15326768/