当我的函数第二次运行时,我得到select中的值,如下所示:
即:我也获得了之前选择的“兴趣轴承检查”选项。我努力尝试但不能解决这个问题。
码
$("select").each(function(i)
{
var $el = $(this);
var $options = $el.find("option:selected");
var prevtext;
var divlength = $('.print-select').length;
if(divlength == 0)
{
$el.after("<select class='print-select' style='color: #2C2C2C; height:30px; width: 231px; margin-left: 409px'><option id=sel"+i+"></option></select>");
var $curPrintBox = $("#sel"+i);
$options.each(function()
{
$curPrintBox.append($(this).text());
prevtext = $(this).text();
alert(prevtext);
});
return false;
}
if(divlength != 0)
{alert("a");
$el
.find(prevtext)
.empty()
.append("<select class='print-select' selected='selected' style='color: #2C2C2C; height:30px; width: 231px; margin-left: 409px'><option>dssd</option></select>");
;
var $curPrintBox = $("#sel"+i);
$options.each(function()
{
$curPrintBox.append($(this).text());
alert($(this).text());
});
}
});
HTML:
<select id="ChangeAccount" style="width: 231px">
<option value="">Select Account Name</option>
<option>Basic Checking</option>
<option>Interest Bearing Checking</option>
<option>Savings</option>
<option>Certificate of Deposit (CD)</option>
<option>Money Market Deposit (MMD)</option>
<option>Individual Retirement (IR)</option>
<option>Other</option>
</select>
答案 0 :(得分:1)
这是您的jquery代码,仅显示所选选项:
$("select#ChangeAccount").on("change", function(){
var $option = $(this).find("option:selected");
$(".print-select").remove();
$(this).after("<div class='print-select'>Selected Option: "+$option.text()+"</div>");
});
但诀窍在于另一个地方:风格。您可以在上面看到的代码option
显示在div
内,其中包含print-select
类。所以你只需要在screen
样式上隐藏该div,然后在print
样式上显示它:
<style type="text/css" media="screen">
.print-select {
display: none;
}
</style>
<style type="text/css" media="print">
.print-select {
display:block;
/* and other props that you want that div to have like border, background... */
}
</style>
答案 1 :(得分:1)
你几乎做得对。只需替换最后一行,如:
$("select").each(function(i)
{
var $el = $(this);
var $options = $el.find("option:selected");
var prevtext;
var divlength = $('.print-select').length;
if(divlength == 0)
{
$el.after("<select class='print-select' style='color: #2C2C2C; height:30px; width: 231px; margin-left: 409px'><option id=sel"+i+"></option></select>");
var $curPrintBox = $("#sel"+i);
$options.each(function()
{
$curPrintBox.append($(this).text());
prevtext = $(this).text();
alert(prevtext);
});
return false;
}
if(divlength != 0)
{alert("a");
$el
.find(prevtext)
.empty()
.append("<select class='print-select' selected='selected' style='color: #2C2C2C; height:30px; width: 231px; margin-left: 409px'><option>dssd</option></select>");
;
var $curPrintBox = $("#sel"+i);
$options.each(function()
{
$curPrintBox.parent().append("<option>"+$(this).text()+"</option>");//change this line
alert($(this).text());
});
}
});