繁体   English   中英

Javascript函数this.title,this.value

[英]Javascript function this.title, this.value

我有一个表单,其中onchange将值传递给javascript函数。 我设法得到this.value和student.value但是this.title没有返回任何内容。

我如何获得选项的标题?

谢谢

<form>
<select id="student" style="width:100%">
<option value="">--</option>
<option value="">A</option>
</select>

<select id="course" onchange="showarchive(this.value, this.title, student.value)" style="width:100%"/>
<option value="">--</option>
<option value="" title="" class=""></option>
</select>
this.options[this.selectedIndex].title

这是所选选项的标题。

这是一个JSFIDDLE

为什么要输入所有这些参数的麻烦呢? 您需要的一切都可以从事件对象中获得,只需更改:

<select id="course" onchange="showarchive(this.value, this.title, student.value)">

至:

<select id="course" onchange="showarchive(event)">

并稍微改变你的功能:

function showarchive (e)
{
    e = e || window.event;//just for safety
    var select = e.target || e.srcElement;//select.id === course now
    var selected = select.options[select.selectedIndex];//your freshly selected option element here
    var title = selected.title;//etc...
    //as an added bonus:
    if (e.preventDefault)
    {
        e.preventDefault();
        e.stopPropagation();
        return e;
    }
    e.returnValue = false;
    e.cancelBubble = true;//redundant: onchange doesn't bubble in IE
}

这样,您就可以访问所需的一切以及更多内容:您可以取消事件本身并操纵其行为。

this onchange方法对应于SELECT对象而不是选定的OPTION对象。 您应该掌握所选的OPTION,然后访问title属性。

你可以得到这样的东西:

function getSelectedText(elementId) {
    var elt = document.getElementById(elementId);

    if (elt.selectedIndex == -1)
        return null;

    return elt.options[elt.selectedIndex].text;
}

并在onchange:

showarchive(this.value, getSelectedText('course'), student.value);

这是一个示例(不同的例子) http://jsfiddle.net/gbsandeep/Dk3nh/

你可以表演

mySelect.options[mySelect.selectedIndex].innerText

获得价值。

暂无
暂无

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

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