时,这才会调用该函数
i具有以下代码,该代码显示警告"未定义",直到在下拉列表中选择选项为止。有没有办法停止出现此消息?
<select id="currency" required>
<option value="" selected disabled>Select Currency</option>
<option value="1,$">USD</option>
<option value="1,£">GBP</option>
</select>
<p><span id='symbol1'></span>0.00</p>
<script>
$(document).ready(currencyFunction);
document.getElementById("currency").addEventListener("change", currencyFunction);
function currencyFunction() {
select=document.getElementById('currency').value.split(',');
display = select[1];
document.getElementById("symbol1").innerHTML = display;
}
</script>
您不应在Document.Ready事件中调用currencyFunction
。
您正在获取undefined
错误,因为准备就绪时正在调用currencyFunction
,并且该功能正在尝试访问下拉列表的值。但是,当页面刚准备好时,下拉列表将选择空值。因此给出了这个错误。
但是,如果您想对错误进行替代,那么请这样做:
function currencyFunction() {
if(document.getElementById('currency').value != '')
{
select=document.getElementById('currency').value.split(',');
display = select[1];
document.getElementById("symbol1").innerHTML = display;
}
}
您在调用页面加载后立即调用该功能变化 :
function currencyFunction() {
select=document.getElementById('currency').value.split(',');
display = select[1];
document.getElementById("symbol1").innerHTML = display;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="currency" required onchange="currencyFunction()">
<option value="" selected disabled>Select Currency</option>
<option value="1,$">USD</option>
<option value="1,£">GBP</option>
</select>
<p><span id='symbol1'></span>0.00</p>
通过在选择标签中使用onchange
事件调用函数,仅当更改选择选项
比JavaScript语法更容易解决:
$(document).on('change', '#currency', function() {
$("#symbol1").html($(this).val())
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="currency" required>
<option value="" selected disabled>Select Currency</option>
<option value="$">USD</option>
<option value="£">GBP</option>
</select>
<p><span id='symbol1'></span>0.00</p>
尝试以下小提琴,
html
<select id="currency" required>
<option value="" selected disabled>Select Currency</option>
<option value="1,$">USD</option>
<option value="1,£">GBP</option>
</select>
<p><span id='symbol1'></span>0.00</p>
JS
$(document).ready(function() {
$('select').on('change', function() {
var valueSelected = this.value.split(',');
console.log(valueSelected[1]);
var temp = $("#symbol1").text().replace(/[^0-9.]/g, "");
$("#symbol1").html(valueSelected[1]+" "+temp);
});
});