我需要跟踪我从1到5中选择的选项。我无法使用值选项,因为我使用它来存储图像。所以我算一下选项的数量。下面的代码在Firefox中很有用,但似乎脚本不能在Chrome或Safari下运行。还没试过IE或者边缘。有什么想法吗?示例:http://rtpcservices.com/count_options.php
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<span>Click a option!</span>
<select id="selected_image" name="selected_image" onchange="
$('#imageToSwap').attr('src', this.options[this.selectedIndex].value);">
<?php
echo '
<option value="' .$shop_name_pdo . '/images/' . $p_image_1 . ' ">Image 1</option>
<option value="' .$shop_name_pdo . '/images/' . $p_image_2 . ' ">Image 2</option>
<option value="' .$shop_name_pdo . '/images/' . $p_image_3 . ' ">Image 3</option>
<option value="' .$shop_name_pdo . '/images/' . $p_image_4 . ' ">Image 4</option>
<option value="' .$shop_name_pdo . '/images/' . $p_image_5 . ' ">Image 5</option>
</select>
';
?>
<script>
$( "option" ).click(function() {
// `this` is the DOM element that was clicked
var index = $( "option" ).index( this );
$( "span" ).text( "Image Selected_option #" + (index+1));
document.getElementById("selected_option").value = index;
});
</script>
答案 0 :(得分:2)
使用更改事件
$( "#selected_image" ).change(function() {
var index = $( "option:selected" ).index();
$( "span" ).text( "Image Selected_option #" + (index+1));
$("#selected_option").val(index);
});
$( "#selected_image" ).change(function() {
var index = $( "option:selected" ).index();
$( "span" ).text( "Image Selected_option #" + (index+1));
$("#selected_option").val(index);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="selected_image" name="selected_image">
<option value="' .$shop_name_pdo . '/images/' . $p_image_1 . ' ">Image 1</option>
<option value="' .$shop_name_pdo . '/images/' . $p_image_2 . ' ">Image 2</option>
<option value="' .$shop_name_pdo . '/images/' . $p_image_3 . ' ">Image 3</option>
<option value="' .$shop_name_pdo . '/images/' . $p_image_4 . ' ">Image 4</option>
<option value="' .$shop_name_pdo . '/images/' . $p_image_5 . ' ">Image 5</option>
</select>
<span></span>
<input type="text" id="selected_option">
答案 1 :(得分:0)
将您的代码更改为以下代码 尝试更改以下行
var index = $( "option" ).index( this );
到
var index = $( "option:selected" ).index( this );