카테고리 없음
[자바 스크립트] MVC3를 사용하여 ActionLink에서 Javascript 함수로 값 전달
행복을전해요
2021. 1. 26. 02:35
무슨 일이 일어나고 있는지 이해하는 방법은 HTML 도우미를 사용하여 앵커 태그를 생성 한 다음 JavaScript를 통해 click
이벤트 를 처리하는 것 입니다. 처리기에서 원본 링크에서 데이터를 가져올 수 있기를 원합니다.
내 제안은 HTML 데이터 주석을 사용하여 데이터를 보관하는 것입니다. 지금 가지고있는 것처럼 매개 변수는 href
경로 매개 변수를 통해 속성 으로 인코딩됩니다 . 대신 HTML 속성으로 이동 data_carrier
하고 프레임 워크를 사용 하면 다음과 같은 앵커 태그가 생성됩니다 (밑줄에서 하이픈으로의 자동 변환이 아님).
@Html.ActionLink("Text", "ActionName", "ControllerName", new { /*route params*/}, new { data_carrier="..." })
결과는 다음과 같습니다.
<a href='...' data-carrier='...'>...</a>
그런 다음 JavaScript에서 매개 변수로 값을 가져 오는 대신 data()
속성에 액세스하려는 jQuery 메소드 또는 원시 JavaScript를 사용하십시오.
var carrier = $(this).data('carrier');
이것이 귀하의 사용 사례를 다룰 것이라고 생각합니다.
-------------------아래 코드 스 니펫은 이 SO 질문 에서 EndangeredMassa에 의해 제공되었습니다 . 문제가 해결 될 것입니다.
<html>
<head>
<script type="text/javascript">
// Wait for the page to load first
window.onload = function() {
//Get a reference to the link on the page
// with an id of "mylink"
var a = document.getElementById("mylink");
//Set code to run when the link is clicked
// by assigning a function to "onclick"
a.onclick = function() {
// Your code here...
//If you don't want the link to actually
// redirect the browser to another page,
// "google.com" in our example here, then
// return false at the end of this block.
// Note that this also prevents event bubbling,
// which is probably what we want here, but won't
// always be the case.
return false;
}
}
</script>
</head>
<body>
<a id="mylink" href="http://www.google.com">linky</a>
</body>
</html>
출처
https://stackoverflow.com/questions/22019899