如何获取任何对象的html中的id名称 [英] how to get the id name in html for any object

查看:65
本文介绍了如何获取任何对象的html中的id名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在img上调用方法onClick函数,我希望该图像ID进一步使用,以便如何访问该图像ID

I am calling method onClick function on the img and i want that image id to use further so how to access that image id

  con.innerHTML += '<table id="results" width="915" border="1" style="margin:-46px 0 0 -2px;"><tr><td><input id="chkbox'+j+'" type="checkbox" name="click_1" value="">&nbsp;'
        + str
        + '</td><td colspan="4" align="right"><a href="javascript:presenter.command(\'viewPdf\',{\'path\': \'/images/pdf/animal/Beef/'+j+'.pdf\'});"><img src="images/view.png" style="margin-left:250px;"></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src="images/email.png" id="'+j+'" onClick=mytest()></td></tr>'+ break_line +'<img src="images/line.png" style="margin-bottom:-47px;"></table>';

这是我要在其中存储图像ID的函数

here is the function i want to store the id of image which is j in this

     function mytest(){

     var ab=document.getElementById('j');

     alert("ali this is wokring fine");

    }

推荐答案

如果您坚持使用内联事件属性,请执行以下操作:

If you insist on using inline event attributes, just do this:

onClick='mytest(this)'

...将对clicked元素的引用传递到您的函数中:

...which passes a reference to the clicked element into your function:

function mytest(clickedElement) {
    var theId = clickedElement.id;
}

然后,您可以访问所涉及元素的任何属性.我已经展示了如何获取 id ,但是您可能不需要 id ,因为如果您已经有了对该元素的引用,显然可以直接使用它-由于它是img,因此您可以例如更改其 src :

You can then access any of the properties of the element in question. I've shown how to get the id, but you may not need the id, because if you already have a reference to the element you can obviously then work with it directly - given that it's an img, you could, for example, change its src:

clickedElement.src = "someotherimg.jpg";

请注意,您根本不需要 getElementById().

Note that you don't then need getElementById() at all.

更新:回答如果?"在评论中,您可以设置 mytest()来接收ID:

UPDATE: To answer the "what if?" in the comment, you can setup mytest() to receive an id:

function mytest(elId) {
    var ab = document.getElementById(elId);
    // etc
}

然后您可以通过 onclick 处理程序将它们都调用:

And then you can call it both from an onclick handler:

onclick='mytest(this.id);'

...,如果已知该ID,则直接在您的代码中:

...and directly in your code if the id is already known:

mytest('1');
mytest('2');
var someId = '3';
mytest(someId);

这篇关于如何获取任何对象的html中的id名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆