简体   繁体   English

如何在javascript中获取动态创建的标签元素的id

[英]How to get the id of a dynamically created label element in javascript

I want to get the text of a dynamically created label in javascript, which is created in jade. 我想在javascript中获取动态创建标签的文本,这是在jade中创建的。 Here's the jade: 这是玉:

- for( var i = 0; i < groupsName.length; i++ ) {
  li
    a(href='JavaScript:validation(this)')
        img(src='/images/edit.png', width='60', height='60', style='margin:8px 10px 10px 20px;')  
         h3 #{groupsName[0]}
          label(for='groupsId' , id='labelid'+i ) #{groupsId[i]}
      a(href='/groupdetails') Edit  
  - }

And this is my javascript code: 这是我的javascript代码:

 function validation(val){
   var valid=val.id;
   alert(document.getElementById(valid).innerHTML);
 }

Not sure if I'm interpreting your template correctly, but as long as the dynamic label is descendant of the anchor tag which triggers the validation this should work: 不确定我是否正确解释您的模板,但只要动态标签是锚标记的后代触发验证,这应该工作:

First replace the href by an onclick otherwise the this being passed will reference the window . 首先更换href通过onclick否则this传递将引用window The generated anchor tag should look like this: 生成的锚标记应如下所示:

<a href="javascript:void(0);" onclick="validation(this);">

Then just adapt your function slightly: 然后稍微调整你的功能:

function validation(anchor) {
    var lbl = anchor.getElementsByTagName('label')[0];
    alert(lbl.innerHTML);
    alert(lbl.id);
}​

Fiddle 小提琴

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

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