Disable anchor tag in knockout.js

2019-04-18 15:01发布

I need to disable the anchor tag inside a foreach loop of knockout.js in HTML.

Here is my code:

<a id="aQStreamSkype" data-bind="attr:{href: ''}, click: $parent.StoreUserClick,disable: ($data.SkypeId == 'null')">Skype </a>

8条回答
Viruses.
2楼-- · 2019-04-18 15:47

Another option that I like to use is to disable the anchor using the "css" directive:

<a id="aQStreamSkype" data-bind="css: { disabled: $data.SkypeId == 'null' }">Skype</a>
查看更多
ら.Afraid
3楼-- · 2019-04-18 15:49

First off, there's a school of thought with which I have some sympathy that says just don't do it. A hyperlink that does nothing is just text.

However, I can see the flip side of the coin - I came across this same problem because I am using a Bootstrap dropdown menu which contains anchor tags as menu options, and to my mind it gives a better user experience to show the menu options as disabled rather than just not show them at all, and I feel it's cleaner to 'disable' the hyperlink than to include markup for a hyperlink and a span with the same text and then conditionally show one or the other. So, my solution was:

<a data-bind="click: checkCondition() ? myFunction : null, css: { disabled: !checkCondition() }"></a>

Note that checkCondition() is a function which returns true or false, indcating whether the hyperlink should be enabled or not. The css binding is just styling the hyperlink to appear disabled - you may have to add your own .disabled CSS class if you're not using Bootstrap.

The key to this working is that the anchor has no href attribute, so it's useless as a hyperlink without the Knockout click binding, which means that you could just as easily use this method with any element type (e.g. this could be a clickable span as easily as an anchor). However, I wanted to use an anchor so that my styling continued to be applied without any extra work.

查看更多
登录 后发表回答