我有一个下拉列表,其中的值超过了当前 div 的宽度。选择该选项后,我只想显示部分文本。我尝试扩展宽度,但表单结构变得一团糟。
<div class="calci-input">
<select id="g-suite-pac-id" name="g-suite-package">
<option value="2.40">$2.40/month</option>
<option value="4.00">$4.00/month</option>
<option value="2.00">$2.00/month(12 months)</option>
<option value="3.33">$3.33/month (12 months)</option>
</select>
</div>
我如何使用 jQuery 实现此目的?
the expected output is that when the option $2.00/month(12 months) is selected it shows as $2.00/month in the drop-down.
最佳答案
该解决方案附带 onchange 和 onmousedown 事件。使用 jQuery 的选择器,我们可以获得选定的选项并更改其显示 HTML。
//you really don't need jQuery, but we can wrap it in there.
//wrap in ready function to make sure page is loaded
$(document).ready(function() {
$("select#g-suite-pac-id").on("change", function() {
var text = $(this).children("option").filter(":selected").text()
var edited = text.match(/^.+?\/month/); //use regex | ^ start, .+? lazy search for everything until /month
//save
$(this).children("option").filter(":selected").data("save", text);
//change
$(this).children("option").filter(":selected").text(edited);
});
$("select#g-suite-pac-id").on("mousedown", function(e) {
//restore a saved value
var selected = $(this).children("option").filter(":selected");
if (selected.length > 0)
{
if (selected.data("save"))
{
selected.text(selected.data("save"));
selected.removeData("save");
}
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="calci-input">
<select id="g-suite-pac-id" name="g-suite-package">
<option value="2.40">$2.40/month</option>
<option value="4.00">$4.00/month</option>
<option value="2.00">$2.00/month(12 months)</option>
<option value="3.33">$3.33/month (12 months)</option>
</select>
</div>
关于javascript - 从选项中选择时更改选项值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46605491/