programing

하이퍼 링크 클릭시 자바 스크립트 함수 호출

nasanasas 2020. 10. 4. 11:29
반응형

하이퍼 링크 클릭시 자바 스크립트 함수 호출


ASP.NET 파일 뒤에있는 C # 코드에서 동적으로 하이퍼 링크를 만들고 있습니다. 클라이언트 클릭시 JavaScript 함수를 호출해야합니다. 어떻게해야합니까?


더 깔끔하게, typical href="#"또는 href="javascript:void"또는 대신 href="whatever"이것이 훨씬 더 의미가 있다고 생각합니다.

var el = document.getElementById('foo');
el.onclick = showFoo;


function showFoo() {
  alert('I am foo!');
  return false;
}

<a href="no-javascript.html" title="Get some foo!" id="foo">Show me some foo</a>

Javascript가 실패하면 피드백이 있습니다. 또한 비정상적인 동작 (의 경우 페이지 점프,의 경우 href="#"동일한 페이지 방문 href="")이 제거됩니다.


가장 간단한 대답은 ...

<a href="javascript:alert('You clicked!')">My link</a>

또는 자바 스크립트 함수 호출에 대한 질문에 답하려면 :

<script type="text/javascript">
function myFunction(myMessage) {
    alert(myMessage);
}
</script>

<a href="javascript:myFunction('You clicked!')">My link</a>


onclick 매개 변수를 사용하면 ...

<a href='http://www.google.com' onclick='myJavaScriptFunction();'>mylink</a>

JQuery 대답. JQuery를 개발하기 위해 JavaScript가 발명 되었기 때문에 다음과 같이 JQuery에서 예제를 제공합니다.

<div class="menu">
    <a href="http://example.org">Example</a>
    <a href="http://foobar.com">Foobar.com</a>
</div>

<script>
jQuery( 'div.menu a' )
    .click(function() {
        do_the_click( this.href );
        return false;
    });

// play the funky music white boy
function do_the_click( url )
{
    alert( url );
}
</script>

I prefer using the onclick method rather than the href for javascript hyperlinks. And always use alerts to determine what value do you have.

<a href='#' onclick='jsFunction();alert('it works!');'>Link</a>

It could be also used on input tags eg.

<input type='button' value='Submit' onclick='jsFunction();alert('it works!');'>


Ideally I would avoid generating links in you code behind altogether as your code will need recompiling every time you want to make a change to the 'markup' of each of those links. If you have to do it I would not embed your javascript 'calls' inside your HTML, it's a bad practice altogether, your markup should describe your document not what it does, thats the job of your javascript.

Use an approach where you have a specific id for each element (or class if its common functionality) and then use Progressive Enhancement to add the event handler(s), something like:

[c# example only probably not the way you're writing out your js]
Response.Write("<a href=\"/link/for/javascriptDisabled/Browsers.aspx\" id=\"uxAncMyLink\">My Link</a>");

[Javascript]  
document.getElementById('uxAncMyLink').onclick = function(e){

// do some stuff here

    return false;
    }

That way your code won't break for users with JS disabled and it will have a clear seperation of concerns.

Hope that is of use.


I would generally recommend using element.attachEvent (IE) or element.addEventListener (other browsers) over setting the onclick event directly as the latter will replace any existing event handlers for that element.

attachEvent / addEventListening allow multiple event handlers to be created.


Use the onclick HTML attribute.

The onclick event handler captures a click event from the users’ mouse button on the element to which the onclick attribute is applied. This action usually results in a call to a script method such as a JavaScript function [...]


If you do not wait for the page to be loaded you will not be able to select the element by id. This solution should work for anyone having trouble getting the code to execute

<script type="text/javascript">
window.onload = function() {
    document.getElementById("delete").onclick = function() {myFunction()};

    function myFunction() {
        //your code goes here
        alert('Alert message here');
    }
};
</script>

<a href='#' id='delete'>Delete Document</a>

참고URL : https://stackoverflow.com/questions/1265887/call-javascript-function-on-hyperlink-click

반응형