使用布尔属性'autofocus'在knockout中使用attr绑定

Max*_*man 7 html5 knockout.js

对于某些属性,存在具有效果的属性 - 分配给它的值无关紧要.例如,autofocus属性可以设置为"false"或"true"或"banana",并且元素仍然会自动聚焦.IE,以下都是等效的,导致div获得焦点:

<div autofocus="false" contenteditable="true"></div>
<div autofocus="true" contenteditable="true"></div>
<div autofocus="banana" contenteditable="true"></div>
Run Code Online (Sandbox Code Playgroud)

Knockout有一个'attr'绑定,但它似乎只对值赋值属性,而不是添加/删除属性.

有没有其他方法在淘汰赛中做到这一点,或者我被迫从javascript设置它?

NB在ubuntu上使用chrome.

bad*_*tax 6

使用布尔值false删除属性,使用字符串'false'设置属性.你还需要什么?

例如:

// Set as boolean, removes the attribute
autofocus(false);   

// Set as boolean, adds the attribute
autofocus(true);  

// Set as string, adds the attribute
autofocus('false');   

// Set as string, adds the attribute
autofocus('true');   
Run Code Online (Sandbox Code Playgroud)

请看这里的例子:http://jsfiddle.net/badsyntax/XMDFh/

  • 你的答案是正确的,但我认为你的描述可以更清晰,更好,答案中的代码并不包含理解答案所需的所有细节.如果JSFiddle离开了,你的代码就不会有用了. (2认同)

Art*_*kov 1

您可以使用hasfocus淘汰赛绑定:

<input data-bind="hasfocus: isSelected" />
Run Code Online (Sandbox Code Playgroud)

在这里阅读更多信息:http ://knockoutjs.com/documentation/hasfocus-binding.html