通过 javascript 检索 onChange 属性的特定属性的值

发布于 2024-12-11 19:54:57 字数 780 浏览 6 评论 0原文

早上好/下午好,

与其说是一个问题,不如说是一个疑问。如果我有以下代码来获取用户在下拉框中的选择(参见图 1),那么如何添加获取特定属性值的功能? (见图 2)

图 1:

<select onChange="productString(this.value)">
    <option selected>Please Choose an Option</option>
    <option value="Foo"></option>
</select>

图 2:

<select onChange="productString(this)">
    <option selected>Please Choose an Option</option>
    <option value="Foo" id="Bar"></option>
</select>

如果有人也能告诉我图 2 中哪里出错了,我将不胜感激。

预先感谢,

丹。

编辑:::::

以下内容可以收集信息吗?

function productString(element) {
    var id = element.value;
    var name = element.id;
    var box = element.class;
}

Good morning/afternoon,

Not so much a problem but more of a query. If I have the following code to grab hold of the users selection on a drop-down box (see figure 1), how do I also add the ability to also grab the value of a specific attribute? (see figure 2)

Figure 1:

<select onChange="productString(this.value)">
    <option selected>Please Choose an Option</option>
    <option value="Foo"></option>
</select>

Figure 2:

<select onChange="productString(this)">
    <option selected>Please Choose an Option</option>
    <option value="Foo" id="Bar"></option>
</select>

If anyone would be so kind as too show me where I am going wrong in figure 2 it would be greatly appreciated.

Thanks in advance,

Dan.

EDIT:::::

Would the following work it collecting the information?

function productString(element) {
    var id = element.value;
    var name = element.id;
    var box = element.class;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

摇划花蜜的午后 2024-12-18 19:54:57

只需通过 this:

<select onChange="productString(this)">

然后你就可以得到你想要的任何东西:

function productString(element) {
  var value = element.value, id = element.id;
  // ...
}

这是一个示例 jsfiddle

编辑 - 哎呀抱歉 - 在 IE 中到处都是(哎呀我一定是瞎了),传递的元素是“select”元素,而不是“option”。因此:

function productString(element) {
    if (element.tagName.toLowerCase() === 'select')
        element = element.options[element.selectedIndex];

    var id = element.id;
    var value = element.value;
    // ...
}

更新了 jsfiddle

Just pass though this:

<select onChange="productString(this)">

and then you can get whatever you want:

function productString(element) {
  var value = element.value, id = element.id;
  // ...
}

Here is a sample jsfiddle.

edit — oops sorry - the element that's being passed through is, in IE everywhere (gee I must be blind), the "select" element, not the "option". Thus:

function productString(element) {
    if (element.tagName.toLowerCase() === 'select')
        element = element.options[element.selectedIndex];

    var id = element.id;
    var value = element.value;
    // ...
}

Updated jsfiddle.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文