javascript 如何获取innerHTML的id值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13341095/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 18:29:33  来源:igfitidea点击:

how to get the value of id of innerHTML?

javascripthtmljavascript-events

提问by Narendra Pal

I have created a html like this.

我已经创建了一个这样的 html。

<body onload = callAlert();loaded()>
<ul id="thelist">
<div id = "lst"></div>          
</ul>
</div>
</body>

The callAlert() is here:

callAlert() 在这里:

function callAlert()
    {
        listRows = prompt("how many list row you want??");
        var listText = "List Number";
                for(var i = 0;i < listRows; i++)
                {
                    if(i%2==0)
                    {
                        listText = listText +i+'<p style="background-color:#EEEEEE" id = "listNum' + i + '" onclick = itemclicked(id)>';
                    }                   
                    else
                    {
                        listText = listText + i+ '<p  id = "listNum' + i + '" onclick = itemclicked(id)>';
                    }                                   
                    listText = listText + i;

                    //document.getElementById("lst").innerHTML = listText+i+'5';
                }
                document.getElementById("lst").innerHTML = listText+i;
    }

Inside callAlert(),I have created id runtime inside the <p>tag and at last of for loop , i have set the paragraph like this. document.getElementById("lst").innerHTML = listText+i;

在 callAlert() 中,我在<p>标签内创建了 id 运行时,最后在 for 循环中,我已经设置了这样的段落。document.getElementById("lst").innerHTML = listText+i;

Now I am confuse when listItem is clicked then how to access the value of the selected item.

现在我很困惑什么时候单击 listItem 然后如何访问所选项目的值。

I am using this:

我正在使用这个:

function itemclicked(id)
    {
        alert("clicked at :"+id);
        var pElement = document.getElementById(id).value;
        alert("value of this is: "+pElement);
    }

But getting value as undefined. Any help would be greatful.

但获得价值为undefined。任何帮助都会很棒。

回答by Varada

try onclick = itemclicked(this.id)instead of onclick = 'itemclicked(id)'

尝试onclick = itemclicked(this.id)代替onclick = 'itemclicked(id)'

回答by Bruno

I am not sure but shouldn't the onclick function be wrapped with double quotes like so:

我不确定但不应该像这样用双引号包裹 onclick 函数:

You have this

你有这个

onclick = itemclicked(id)>'

And it should be this

应该是这个

onclick = "itemclicked(id)">'

You have to modify your itemclicked function to retrieve the "value" of your p element.

您必须修改 itemclicked 函数以检索 p 元素的“值”。

function itemclicked( id ) {

    alert( "clicked at :" + id );
    var el = document.getElementById( id );

    // depending on the browser one of these will work
    var pElement = el.contentText || el.innerText; 

    alert( "value of this is: " + pElement );
}

demo here

演示在这里

回答by nozzleman

Dude, you should really work on you CodingStyle. Also, write simple, clean code.

伙计,你真的应该在你的 CodingStyle 上工作。另外,编写简单、干净的代码。

First, the html-code should simply look like this:

首先,html 代码应该如下所示:

    <body onload="callAlert();loaded();">
        <ul id="thelist"></ul>
    </body>

No div or anything like this. uland olshall be used in combination with lionly. Also, you should always close the html-tags in the right order. Otherwise, like in your examle, you have different nubers of opening and closing-tags. (the closing divin the 5th line of your html-example doesn't refer to a opening div-tag)...

没有 div 或类似的东西。ul并且只能ol与组合使用li。此外,您应该始终以正确的顺序关闭 html 标签。否则,就像在你的例子中一样,你有不同的开始和结束标签。(div你的 html-example 的第 5 行的结束不是指一个开始的 div 标签)......

And here comes the fixed code:

这是固定代码:

    <script type="text/javascript">
         function callAlert() {
            var rows = prompt('Please type in the number of required rows');
            var listCode = '';
            for (var i = 0; i < rows; i++) {
                var listID = 'list_' + i.toString();
                if (i % 2 === 0) {
                    listCode += '<li style="background-color:#EEEEEE" id="' + listID + '" onclick="itemClicked(this.id);">listItem# ' + i + '</li>';
                }
                else {
                    listCode += '<li id="' + listID + '" onclick="itemClicked(this.id);">listItem# ' + i + '</li>';
                }
            }
            document.getElementById('thelist').innerHTML = listCode;
        }

        function itemClicked(id) {
            var pElement = document.getElementById(id).innerHTML;
            alert("Clicked: " + id + '\nValue: ' + pElement);
        }
    </script>

You can watch a working sample in this fiddle.

您可以在这个fiddle 中观看工作示例。

The problems were:

问题是:

  1. You have to commit the id of the clicked item using this.idlike @Varada already mentioned.
  2. Before that, you have to build a working id, parsing numbers to strings using .toString()
  3. You really did write kind of messy code. What was supposed to result wasn't a list, it was various div-containers wrapped inside a ul-tag. Oh my.
  1. 您必须使用this.id已经提到的@Varada来提交被点击项目的 id 。
  2. 在此之前,您必须构建一个工作 id,使用以下命令将数字解析为字符串 .toString()
  3. 你确实写了一些凌乱的代码。应该产生的结果不是列表,而是div包裹在ul-tag 中的各种-containers。天啊。

BTW: Never ever check if sth. is 0using the ==-operator. Better always use the ===-operator. Read about the problem here

BTW:永远不要检查是否…… 正在0使用 -==运算符。最好始终使用 -===运算符。在此处阅读有关问题的信息

BTW++: I don't know what valueyou wanted to read in your itemClicked()-function. I didn't test if it would read the innerHTMLbut generally, you can only read information from where information was written to before. In this sample, valueshould be empty i guess..

BTW++:我不知道value你想在你的itemClicked()-function 中读到什么。我没有测试它是否会读取,innerHTML但一般来说,您只能从之前写入信息的位置读取信息。在这个示例中,value我猜应该是空的..

Hope i didn't forget about anything. The Code works right now as you can see. If you've got any further questions, just ask.

希望我没有忘记任何事情。如您所见,该代码现在可以正常工作。如果您有任何进一步的问题,请提问。

Cheers!

干杯!

回答by Alessandro Minoccheri

You can pass only the var iand search the id after like this:

您可以只传递 vari并在这样之后搜索 id:

Your p constructor dymanic with passing only i

你的 p 构造函数 dymanic 只传递 i

<p  id = "listNum' + i + '" onclick = itemclicked(' + i + ')>

function

功能

function itemclicked(id)
    {
        id='listNum'+i;
        alert("clicked at :"+id);
        var pElement = document.getElementById(id).value;
        alert("value of this is: "+pElement);
    }

is what you want?

是你想要的吗?