함수를 호출 한 요소의 ID 가져 오기
JS 함수를 호출 한 요소의 ID를 어떻게 얻을 수 있습니까?
body.jpg 는 사용자가 신체의 다른 부분에서 화면 주위를 마우스로 가리키면 확대 된 이미지가 표시되는 강아지의 이미지입니다. 영역 요소의 ID는 폴더 및 확장자를 뺀 이미지 파일 이름과 동일합니다.
<div>
<img src="images/body.jpg" usemap="#anatomy"/>
</div>
<map name="anatomy">
<area id="nose" shape="rect" coords="280,240,330,275" onmouseover="zoom()"/>
</map>
<script type="text/javascript">
function zoom()
{
document.getElementById("preview").src="images/nose.jpg";
}
</script>
<div>
<img id="preview"/>
</div>
나는 내 연구를 마쳤고 마지막 수단으로 Stack Overflow에 왔습니다. jQuery를 포함하지 않는 솔루션을 선호합니다.
호출 될 때 요소에 대한 참조를 함수에 전달하십시오.
<area id="nose" onmouseover="zoom(this);" />
<script>
function zoom(ele) {
var id = ele.id;
console.log('area element id = ' + id);
}
</script>
아무도 this
이벤트 핸들러에서 사용에 대해 언급하지 않았다는 사실에 놀랐습니다 . 최신 브라우저에서 자동으로 작동하며 다른 브라우저에서도 작동하도록 만들 수 있습니다. 당신이 사용하는 경우 addEventListener
또는 attachEvent
이벤트 핸들러를 설치, 당신은의 값을 만들 수 있습니다 this
자동으로 이벤트를 생성 한 개체에 할당 할 수 있습니다.
또한 프로그래밍 방식으로 설치된 이벤트 처리기를 사용하면 종종 좋은 것으로 간주되는 HTML에서 자바 스크립트 코드를 분리 할 수 있습니다.
일반 자바 스크립트에서 코드를 작성하는 방법은 다음과 같습니다.
onmouseover="zoom()"
HTML에서를 제거하고 다음과 같이 자바 스크립트에 이벤트 핸들러를 설치합니다.
// simplified utility function to register an event handler cross-browser
function setEventHandler(obj, name, fn) {
if (typeof obj == "string") {
obj = document.getElementById(obj);
}
if (obj.addEventListener) {
return(obj.addEventListener(name, fn));
} else if (obj.attachEvent) {
return(obj.attachEvent("on" + name, function() {return(fn.call(obj));}));
}
}
function zoom() {
// you can use "this" here to refer to the object that caused the event
// this here will refer to the calling object (which in this case is the <map>)
console.log(this.id);
document.getElementById("preview").src="http://photos.smugmug.com/photos/344290962_h6JjS-Ti.jpg";
}
// register your event handler
setEventHandler("nose", "mouseover", zoom);
이벤트 핸들러에서 'this'를 사용할 수 있습니다.
document.getElementById("preview").onmouseover = function() {
alert(this.id);
}
또는 다음과 같이 이벤트 객체를 핸들러에 전달합니다.
document.getElementById("preview").onmouseover = function(evt) {
alert(evt.target.id);
}
It's recommended to use attachEvent(for IE < 9)/addEventListener(IE9 and other browsers) to attach events. Example above is for brevity.
function myHandler(evt) {
alert(evt.target.id);
}
var el = document.getElementById("preview");
if (el.addEventListener){
el.addEventListener('click', myHandler, false);
} else if (el.attachEvent){
el.attachEvent('onclick', myHandler);
}
You can code the handler setup like this:
<area id="nose" shape="rect" coords="280,240,330,275" onmouseover="zoom.call(this)"/>
Then this
in your handler will refer to the element. Now, I'll offer the caveat that I'm not 100% sure what happens when you've got a handler in an <area>
tag, largely because I haven't seen an <area>
tag in like a decade or so. I think it should give you the image tag, but that could be wrong.
edit — yes, it's wrong - you get the <area>
tag, not the <img>
. So you'll have to get that element's parent (the map), and then find the image that's using it (that is, the <img>
whose "usemap" attribute refers to the map's name).
edit again — except it doesn't matter because you want the area's "id" durr. Sorry for not reading correctly.
I know you don't want a jQuery solution but including javascript inside HTML is a big no no.
I mean you can do it but there are lots of reasons why you shouldn't (read up on unobtrusive javascript if you want the details).
So in the interest of other people who may see this question, here is the jQuery solution:
$(document).ready(function() {
$('area').mouseover(function(event) {
$('#preview').attr('src', 'images/' + $(event.srcElement).attr('id'));
});
});
The major benefit is you don't mix javascript code with HTML. Further more, you only need to write this once and it will work for all tags as opposed to having to specify the handler for each separately.
Additional benefit is that every jQuery handler receives an event object that contains a lot of useful data - such as the source of the event, type of the event and so on making it much easier to write the kind of code you are after.
Finally since it's jQuery you don't need to think about cross-browser stuff - a major benefit especially when dealing with events.
i also want this to happen , so just pass the id of the element in the called function and used in my js file :
function copy(i,n)
{
var range = document.createRange();
range.selectNode(document.getElementById(i));
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
document.execCommand('copy');
window.getSelection().removeAllRanges();
document.getElementById(n).value = "Copied";
}
참고URL : https://stackoverflow.com/questions/7627161/get-id-of-element-that-called-a-function
'IT TIP' 카테고리의 다른 글
상속을 사용하는 이유는 무엇입니까? (0) | 2020.12.04 |
---|---|
nginx 502 잘못된 게이트웨이 (0) | 2020.12.04 |
클러스터를 사용하여 Socket.IO를 여러 Node.js 프로세스로 확장 (0) | 2020.12.04 |
Visual Studio 프로젝트의 ipch 파일 (0) | 2020.12.04 |
빌드 도구를 21.0.1로 업그레이드하는 Android Gradle 프로젝트 : aapt에서 예외 발생 (0) | 2020.12.04 |