Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
456 views
in Technique[技术] by (71.8m points)

javascript - Close Bootstrap Dropdown after link click

I have a bootstrap dropdown menu below. It has a link in it hooked up to a knockout.js binding, that returns false because I don't want the # tag to be sent to the browser URL. However, doing this doesn't close the dropdown menu when I click the link. Any way around this?

HTML

<div class="btn-group">
    <button class="btn dropdown-toggle" data-toggle="dropdown" data-bind="enable: !noResults()"><i class="icon-download-alt" ></i> Export <span class="icon-caret-down"></span></button>

    <ul class="dropdown-menu">
        @foreach(var exportUrl in Model.ExportUrls)
        {
            <li>
                <a href="#" data-bind="disable: noResults(), download: { url: '@exportUrl.Value', data: data }"><img src="/Content/less/images/img/@(exportUrl.Key.ToString().ToLower()).png" alt="@exportUrl.Key.GetDisplayName()"/> @exportUrl.Key.GetDisplayName()</a>
            </li>
        }
    </ul>
</div>

knockut.js binding

ko.bindingHandlers.download = {
    init: function (element, valueAccessor) {

        var value = ko.utils.unwrapObservable(valueAccessor()),
            id = 'download-iframe-container',
            iframe;

        $(element).unbind('click').bind('click', function () {

            iframe = document.getElementById(id);

            if (!iframe) {
                iframe = document.createElement("iframe");
                iframe.id = id;
                iframe.style.display = "none";
            }

            if (value.data) {
                iframe.src = value.url + (value.url.indexOf('?') > 0 ? '&' : '?') + $.param(ko.mapping.toJS(value.data));
            } else {
                iframe.src = value.url;
            }

            document.body.appendChild(iframe);

            return false;
        });
    }
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Give your links a class (e.g. download):

<a href="#" class="download" data-bind="disable: noResults()....

And your dropdown an id (e.g. dlDropDown):

<button class="btn dropdown-toggle" id="dlDropDown" data-toggle="dropdown" data-bind="enable: !noResults()">

And then add the following event handler:

$("a.download").click(function() {
   $("#dlDropDown").dropdown("toggle");
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...