jQuery:访问(多).attr()

jQuery: accessing (multi) .attr()

我在访问(多个).attr(...) 的信息时遇到问题 我找到 this 并尝试对其进行调整 - 但它不起作用。我在这里遗漏了一些明显的东西(js 的新手)。希望能在这里找到帮助!

var user_id = document.getElementById('myselect').options[select.selectedIndex].user_id;
var user_email = document.getElementById('myselect').options[select.selectedIndex].user_email;

document.getElementById('display').innerHTML = 'User with ID' + user_id + " has email address " + user_email;
<select id="myselect">
  <option user_email="test@test.de" user_id=1>Test 0</option>
  <option user_email="email@email.de" user_id=1>Test 1</option>
  <option user_email="whyso@serious.de" user_id=1>Test 3</option>
</select>

<div id="display"></div>

试试这个:

var index = document.getElementById('myselect').selectedIndex;
var user_id = document.getElementById('myselect').options[index].getAttribute('user_id');
var user_email = document.getElementById('myselect').options[index].getAttribute('user_email');

document.getElementById('display').innerHTML = 'User with ID' + user_id + " has email address " + user_email;

select.selectedIndex 在您的示例中不存在。这应该有效:

var select = document.getElementById('myselect');

var user_id = select.options[select.selectedIndex].getAttribute('user_id');
var user_email = select.options[select.selectedIndex].getAttribute('user_email');

document.getElementById('display').innerHTML = 'User with ID' + user_id + " has email address " + user_email;