2017-03-16 1 views
1

사용자가 현재 페이지에 있다면 버튼을 비활성화하려고합니다. 더 효율적인 방법이 있지만 if, elses를 연습하고 있습니다.내 jquery 버튼을 비활성화하지 않는 이유는 무엇입니까

문제는 내가 링크를 클릭 할 수 있고 클릭하면 페이지가 새로 고침되고 동일한 페이지에 있다는 것입니다. 내 코드 :

$("#homepage").on("click", function(event) { 
 
    if (window.location.href === 'index.html') { 
 
     $(this).attr('disabled', "disabled"); 
 
     $(this).attr('disabled', true); 
 
     event.preventDefault(); 
 
    }else { 
 
     window.location.href = 'index.html'; 
 
    }; 
 
}); \t 
 
$("#aboutUs").on("click", function(event) { 
 
    if (window.location.href === 'aboutus.html') { 
 
     $(this).attr('disabled', "disabled"); 
 
     $(this).attr('disabled', true); 
 
     event.preventDefault(); 
 
    }else { 
 
     window.location.href = 'aboutus.html'; 
 
    }; 
 
});

+0

'window.location.href'가 무엇인지 기록하십시오. ''index.html '' –

+1

''console.log (window.location.href)'를 확인하고 그 결과를 확인하십시오. 나는 그것이 다른 무엇인가라고 생각한다. 그리고 그것이 if 조건이 결코 성공하지 않는 이유 다. –

+0

@AlivetoDie 예를 들어 Google 크롬에서로드되면 'file : // C : \ Users \ admin \ Desktop \ MyWebsite \ index.html'이됩니다. 서버 나 정규 IP 주소 인'142.153.31.22/index.html'에서'https : // www.example.com/index.html'과 같을 것이고 결코 ** 단지 "index.html이 아닙니다 " –

답변

0

사실 window.location.href을 통해 완전한 활약을 선사 할 것입니다. D의 URL과 같은 : -

https://www.example.com/index.html 

http://www.example.com/index.html 

당신의 if 조건이 참이 결코 것으로 보인다 이유

.

사용 indexOf() 다음과 같은 : -

$("#homepage").on("click", function(event) { 
    if (window.location.href.indexOf('index.html') >-1) { 
      $(this).prop('disabled', true); // recomended to use `prop` 
      event.preventDefault(); 
    } 
    else { 
     window.location.href = 'index.html'; 
    } 
}); 
$("#aboutUs").on("click", function(event) { 
    if (window.location.href.indexOf('aboutus.html')>-1) { 
     $(this).prop('disabled', true);// recomended to use `prop` 
     event.preventDefault(); 
    } 
    else { 
     window.location.href = 'aboutus.html'; 
    } 
}); 

참조 : -

indexOf() functionality

당신 만이 특정 URL 'S의 버튼을 해제하여 제공 한 if 상태에서 전체 경로를 사용하려면 console.log(window.location.href);.

+0

안녕하세요 .indexOf ('index.html')> -1이 어떻게되는지 설명하는 쉬운 방법이 있습니다. 일하다? 또는 내 방식을 가리킬 수있는 몇 가지 문서? –

+0

그 문서를 찾았는데, 난 단지 .indexOf를이 방법으로 링크와> -1로 사용하지 않았고, 설명서를 보면서 내 머리를 감쌀 수 있기를 바랍니다. 감사합니다. –

+0

안녕하세요. 본질적으로 -1> -1로 실행하지만 왜 -1이 아닌지 === -1? –

0

$("#homepage").on("click", function(event) { 
alert(window.location.href); 
}); 

같은 window.location.href의 값이이 값을 넣어보다 무엇을 확인하면 상태 등 :

if (window.location.href === 'dummyrul/index.html') { 
       $(this).attr('disabled', "disabled"); 
       $(this).attr('disabled', true); 
       event.preventDefault(); 
      } 
+0

@Christian A this를 시도하십시오 – Faraz

관련 문제