简体   繁体   English

JavaScript-如何获取元素的ID

[英]JavaScript - How do i get ID of Element

<div id="block_msg" style="width:250px;border: solid 1px red;margin: 15px">

<div id="text_msg1">111текст111</div>

<input type="submit" onclick="clickon(**<<<HERE I WANT SEE DIV ID TEXT_MSG1>>>**)" value="Добавить">

</div>

How i can get id="text_msg1" and put it into onclick. 我如何获得id =“ text_msg1”并将其放入onclick。 How? 怎么样? Thanks! 谢谢!

this is the current object, you can than look at the parent and find the divs. this是当前对象,然后您可以查看父对象并找到div。 This solution is hacky since changing the layout means it will break. 该解决方案很麻烦,因为更改布局意味着它会损坏。

onclick="clickon(this)"

and

function clickon(btn) {
    var wrappingDiv = btn.parentNode;
    var childrenDivs = wrappingDiv.getElementsByTagName("div");
    alert(childrenDivs[0].innerHTML);
}

JSFiddle JSFiddle

It would be better to have a class on the div and look for that class. 最好在div上有一个类并寻找该类。

If you want to get the previous element sibling, traverse the DOM until you find it: 如果要获得先前的元素同级,请遍历DOM,直到找到它:

function get_previous_element_sibling(element) {
    var prev = element.previousSibling;

    while (prev && prev.nodeType !== 1) {
        prev = prev.previousSibling;
    }

    return prev;
}

Then you can get the previous sibling with: 然后,您可以使用以下命令获得先前的兄弟姐妹:

get_previous_element_sibling(this)

and its ID with 和它的ID

get_previous_element_sibling(this).id

Based on your comment yes, preceding! this line 根据您的评论, yes, preceding! this line yes, preceding! this line will not work with IE8 and lower because of previousElementSibling 由于previousElementSibling yes, preceding! this line不适用于IE8和更低版本

<input type="submit" onclick="clickon(this.previousElementSibling.id)" value="Добавить">

or using jQuery for cross browser support 或使用jQuery来支持跨浏览器

<input type="submit" onclick="clickon($(this).prev().attr('id'))" value="Добавить">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM