Programing

jQuery를 사용하여 앵커를 활성화 또는 비활성화하는 방법은 무엇입니까?

lottogame 2020. 6. 12. 22:06
반응형

jQuery를 사용하여 앵커를 활성화 또는 비활성화하는 방법은 무엇입니까?


jQuery를 사용하여 앵커를 활성화 또는 비활성화하는 방법은 무엇입니까?


앵커가 지정된을 따르지 못하게하려면 다음을 사용하는 href것이 좋습니다 preventDefault().

// jQuery 1.7+
$(function () {
    $('a.something').on("click", function (e) {
        e.preventDefault();
    });
});

// jQuery < 1.7
$(function () {
    $('a.something').click(function (e) {
        e.preventDefault();
    });

    // or 

    $('a.something').bind("click", function (e) {
        e.preventDefault();
    });
});

보다:

http://docs.jquery.com/Events/jQuery.Event#event.preventDefault.28.29

SO에 대한이 이전 질문을 참조하십시오.

jQuery는 링크를 비활성화


현재 작업중 인 앱은 자바 스크립트와 함께 CSS 스타일로 수행합니다.

a.disabled { color:gray; }

그런 다음 링크를 비활성화 할 때마다 전화합니다.

$('thelink').addClass('disabled');

그런 다음 'thelink'에 대한 클릭 핸들러에서 태그를 항상 확인합니다.

if ($('thelink').hasClass('disabled')) return;

나는 여기서 훨씬 더 좋아하는 답을 찾았다.

다음과 같습니다 :

$(document).ready(function(){
    $("a").click(function () { 
        $(this).fadeTo("fast", .5).removeAttr("href"); 
    });
});

활성화하려면 href 속성을 설정해야합니다.

$(document).ready(function(){
    $("a").click(function () { 
        $(this).fadeIn("fast").attr("href", "http://whatever.com/wherever.html"); 
    });
});

그러면 앵커 요소가 일반 텍스트가되고 그 반대도 마찬가지입니다.


$("a").click(function(){
                alert('disabled');
                return false;

}); 

더 좋은 해결책은 비활성화 된 데이터 속성을 설정하고 클릭시 확인하는 것입니다. 이 방법으로 자바 스크립트가 아약스 호출이나 일부 계산으로 끝날 때까지 앵커를 일시적으로 비활성화 할 수 있습니다. 비활성화하지 않으면 몇 번 빠르게 클릭 할 수 있으므로 바람직하지 않습니다 ...

$('a').live('click', function () {
    var anchor = $(this);

    if (anchor.data("disabled")) {
        return false;
    }

    anchor.data("disabled", "disabled");

    $.ajax({
        url: url,
        data: data,
        cache: false,
        success: function (json) {
            // when it's done, we enable the anchor again
            anchor.removeData("disabled");
        },
        error: function () {
             // there was an error, enable the anchor
            anchor.removeData("disabled");
        }
    });

    return false;
});

나는 jsfiddle 예제를 만들었다 : http://jsfiddle.net/wgZ59/76/


선택된 답변이 좋지 않습니다.

포인터 이벤트 CSS 스타일을 사용하십시오 . (Rashad Annara가 제안한대로)

MDN https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events를 참조 하십시오 . 대부분의 브라우저에서 지원됩니다.

앵커에 "disabled"속성을 추가하면 다음과 같은 전역 CSS 규칙이있는 경우 작업을 수행합니다.

a[disabled], a[disabled]:hover {
   pointer-events: none;
   color: #e1e1e1;
}

아래 줄을보십시오

$("#yourbuttonid").attr("disabled", "disabled");
$("#yourbuttonid").removeAttr("href");

Coz, Even if you disable <a> tag href will work so you must remove href also.

When you want enable try below lines

$("#yourbuttonid").removeAttr("disabled");
$("#yourbuttonid").attr("href", "#nav-panel");

It's as simple as return false;

ex.

jQuery("li a:eq(0)").click(function(){
   return false;
})

or

jQuery("#menu a").click(function(){
   return false;
})

$('#divID').addClass('disabledAnchor');

In css file

.disabledAnchor a{
       pointer-events: none !important;
       cursor: default;
       color:white;
}

$("a").click(function(event) {
  event.preventDefault();
});

If this method is called, the default action of the event will not be triggered.


If you are trying to block all interaction with the page you might want to look at the jQuery BlockUI Plugin


You never really specified how you wanted them disabled, or what would cause the disabling.

First, you want to figure out how to set the value to disabled, for that you would use JQuery's Attribute Functions, and have that function happen on an event, like a click, or the loading of the document.


For situations where you must put text or html content within an anchor tag, but you simply don't want any action to be taken at all when that element is clicked (like when you want a paginator link to be in the disabled state because it's the current page), simply cut out the href. ;)

<a>3 (current page, I'm totally disabled!)</a>

The answer by @michael-meadows tipped me off to this, but his was still addressing scenarios where you still have to / are working with jQuery/JS. In this case, if you have control over writing the html itself, simply x-ing the href tag is all you need to do, so the solution is a pure HTML one!

Other solutions without jQuery finagling which keep the href require you to put a # in the href, but that causes the page to bounce to the top, and you just want it to be plain old disabled. Or leaving it empty, but depending on browser, that still does stuff like jump to the top, and, it is invalid HTML according to the IDEs. But apparently an a tag is totally valid HTML without an HREF.

Lastly, you might say: Okay, why not just dump the a tag altogether than? Because often you can't, the a tag is used for styling purposes in the CSS framework or control you're using, like Bootstrap's paginator:

http://twitter.github.io/bootstrap/components.html#pagination


So with a combination of the responses above, I came up with this.

a.disabled { color: #555555; cursor: default; text-decoration: none; }

$(".yourClass").addClass("disabled").click(function(e){ e.preventDefault(); 

If you don't need it to behave as an anchor tag then I would prefer to replace it at all. For example if your anchor tag is like

<a class="MyLink" href="http://www.google.com"><span>My</span> <strong>Link</strong></a>

then using jquery you can do this when you need to display text instead of a link.

var content = $(".MyLink").text(); // or .html()
$(".MyLink").replaceWith("<div>" + content + "</div>")

So this way, we can simply replace anchor tag with a div tag. This is much easier (just 2 lines) and semantically correct as well (because we don't need a link now therefore should not have a link)


Disable or Enable any element with the disabled property.

// Disable 
$("#myAnchor").prop( "disabled", true );

// Enable
$( "#myAnchor" ).prop( "disabled", false );

참고URL : https://stackoverflow.com/questions/1164635/how-to-enable-or-disable-an-anchor-using-jquery

반응형