如何在js中获取元素的内容


How can I get the content of an element in js?

我正在尝试获取选项元素的值和内容。到目前为止,我已经使用this.value获得了如下所示的值

<select name='name' id='name' onchange='someFunction(this.value)'>
    <option selected='selected' disabled='disabled' value=''>CONTENT</option>
     " . $options . "
</select>";

我可以在值处传递onchange事件上的"内容"吗?

像这样的事情也许。。。onchange='showAccountInfo(this.value, ???)

任何帮助都会很棒,谢谢!

<select name='name' id='name' onchange='someFunction(this)'>
    <option selected='selected' disabled='disabled' value=''>CONTENT</option>
     " . $options . "
 </select>"
 function someFunction(obj)
 {
     var value = obj.value;
     var content = obj.querySelector("option:checked").textContent;
 }

这应该做到:

我更改了onchange函数中传递的对象。它使用关键字this将select对象传递给函数。然后,我们使用value来选择值,并使用querySelector使用选择器option:checked来选择所选选项。通过这种方式,您的代码变得更加可读。

然而,您可以将其存储在onchange中,如下所示:

onchange='showAccountInfo(this.value, this.querySelector("option:checked").textContent)'

就我个人而言,我不会使用(或建议)内联事件。

我会用addEventListener:这样做

     function someFunction(e)
     {
        //this refers to the select element (the owner of the event);
         var value = this.value;
         var content = this.querySelector("option:checked").textContent;
         alert("value: " + value + " content: " + content);
     }
     document.querySelector("#name").addEventListener("change", someFunction, false); //attach an onchange event using the addEventListener method.
//I'm using document.querySelector here to select an element on the page.
    <select name='name' id='name' >
        <option selected='selected'  value='1:'>CONTENT 1</option>
        <option value='2:'>CONTENT 2</option>
        <option value='3:'>CONTENT 3</option>
        <option value='4:'>CONTENT 4</option>
     </select>