jQuery:改变选项选择的跨度值

jQuery : change span value on option select

本文关键字:选择 改变 选项 jQuery      更新时间:2023-09-26

为客户做项目…我想根据下拉框的选择来改变#sandy的跨度值。例如,如果选择了选项文本1,span #sandy会显示:"This is for #sandy2",如果选择了选项文本2,span #sandy会显示:"This is NOT for #sandy2"。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>SANDBOX TEST</title>
<script>
function checkField(val)
{
alert("The input value has changed. The new value is: " + val);
}
</script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
i = 0;
$(document).ready(function () {
    $("#clientname").keyup(function () {
        $("#pizza").text(i += 1);
        var stt = $(this).val();
        $("#sandy2").text(stt);
    });
});
</script>
</head>
<body>
<p>Modify the text in the input field, then click outside the field to fire onchange.    </p>
<table style="width: 300px">
<tr>
    <td style="width: 150px">Enter some text: </td>
    <td> 
    <input type="text" name="txt" id="clientname" value="" onchange="checkField(this.value)" style="width: 150px"/></td>
</tr>
<tr>
    <td style="width: 150px">Selection:</td>
    <td> <select name="Select1" style="width: 150px" onchange="jsFunction()">
            <option value="" disabled selected style="display:none;">Choose An Option!</option>
            <option>Option Text 1</option>
            <option>Option Text 2</option>
        </select></td>
</tr>
</table>
<br/>
======================================
<br/>
<span id="sandy">This is a test for <span id="sandy2"></span></span>
</body>
</html>

select一个id,并给每个选项一个值:

<select id="selector" name="Select1" style="width: 150px" onchange="jsFunction()">
        <option value="" disabled selected style="display:none;">Choose An Option!</option>
        <option value="1">Option Text 1</option>
        <option value="2">Option Text 2</option>
</select>

select被改变时,你可以得到这样的选择值:

var selected = $('#selector option:selected').val();

然后在您的更改处理程序中,或者您的keyup处理程序中,您可以获得选定的值并相应地执行操作。


此外,将内联处理程序与jQuery混合使用是不好的做法。

行删除onchange
<select id="selector" name="Select1" style="width: 150px" onchange="jsFunction()">

,然后像这样添加:

$(function() {
  $('#selector').on('change', jsFunction);
});

我不明白你的意思。但我所理解的一切。或者你可以看到http://jsfiddle.net/X83ex/1/

<select name="Select1" id="selection" style="width: 150px" onchange="jsFunction(this)">
        <option value="" disabled selected style="display:none;">
          Choose An Option!       
       </option>
        <option>Option Text 1</option>
        <option>Option Text 2</option>
    </select>

你可以在javascript中这样写:

function jsFunction(that){
    $('#sandy2').text($(that).val());
}