[javascript] HTML 태그 <a>가 href와 onclick을 모두 추가하려고합니다.

HTML 태그에 대해 묻고 싶습니다.

<a href="www.mysite.com" onClick="javascript.function();">Item</a>

이것을 hrefonClick 과 함께 작동 하는 태그 로 만드는 방법은 무엇입니까? (먼저 onClick을 실행 한 다음 href를 선호)



답변

약간의 구문 변경으로 필요한 것을 이미 가지고 있습니다.

<a href="www.mysite.com" onclick="return theFunction();">Item</a>

<script type="text/javascript">
    function theFunction () {
        // return true or false, depending on whether you want to allow the `href` property to follow through or not
    }
</script>

의 기본 동작 <a>태그의 onclickhref속성을 실행하는 것입니다 onclick, 다음을 따라 href만큼이 같은 onclick반환하지 않는 false이벤트를 취소 (또는 이벤트가 방지되지 않은)


답변

jQuery를 사용하십시오 . click이벤트 를 캡처 한 다음 웹 사이트로 이동해야합니다.

$("#myHref").on('click', function() {
  alert("inside onclick");
  window.location = "http://www.google.com";
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" id="myHref">Click me</a>


답변

이를 달성하려면 다음 html을 사용하십시오.

<a href="www.mysite.com" onclick="make(event)">Item</a>

<script>
    function make(e) {
        // ...  your function code
        // e.preventDefault();   // use this to NOT go to href site
    }
</script>

다음은 작업 예 입니다.


답변

jQuery가 필요하지 않습니다.

어떤 사람들은 사용 onclick이 나쁜 습관 이라고 말합니다 …

이 예제는 순수 브라우저 자바 스크립트를 사용합니다. 기본적으로 탐색 전에 클릭 핸들러가 평가되는 것으로 보이므로 탐색을 취소하고 원하는 경우 직접 수행 할 수 있습니다.

<a id="myButton" href="http://google.com">Click me!</a>
<script>
    window.addEventListener("load", () => {
        document.querySelector("#myButton").addEventListener("click", e => {
            alert("Clicked!");
            // Can also cancel the event and manually navigate
            // e.preventDefault();
            // window.location = e.target.href;
        });
    });
</script>


답변

사용 ng-click대신에 onclick. 다음과 같이 간단합니다.

<a href="www.mysite.com" ng-click="return theFunction();">Item</a>

<script type="text/javascript">
function theFunction () {
    // return true or false, depending on whether you want to allow 
    // the`href` property to follow through or not
 }
</script>


답변