HTML
<div>
<input type='text' id='ccType' name='ccType'/>
<ul style="list-style-type: none;" class="cards">
<li class="visa"></li>
<li class="visa_electron"></li>
<li class="mastercard"></li>
<li class="maestro"></li>
</ul>
</div>
<div class="form-group">
<label class="control-label">Card Number</label>
</div>
<div class="fake-input">
<input type="text" placeholder="Card Number" id="ccnumber" name="ccnumber" class="form-control"/>
<img id="cc" src="" width=30 />
</div>
我有这个 html,它有一个文本字段,当输入卡号时,它会检测卡号是否是 visa/maestro/whatever 并将值设置为 ccType 元素。我有一个 javascript JS
$( window ).load(function() {
$("#ccType").on('change', function () {
var ccType = $(this).val();
if (ccType == "visa") {
$('#cc').attr('src', 'http://www.fethr.com/webapp/images/visa.png');
}
if (ccType == "maestro") {
$('#cc').attr('src', 'http://www.fethr.com/webapp/images/maestro.png');
}
if (ccType == "mastercard") {
$('#cc').attr('src', 'http://www.fethr.com/webapp/images/mastercard.png');
}
if (ccType == "visa_electron") {
$('#cc').attr('src', 'http://www.fethr.com/webapp/images/visaelectron.png');
}
})
});
我在文本字段中设置图像。我有以下 img 和文本字段的 css CSS
.fake-input { position: relative; }
.fake-input input { border:none: background:#fff; display:block; width: 100%; box-sizing: border-box }
.fake-input img { position: absolute; top: 9px; right: 5px }
但是图像脚本似乎不起作用,或者我无法在文本字段中显示图像? 任何帮助
fiddle
最佳答案
这是因为您将事件监听器放在 window.load 事件中,并且它在文本字段进入 DOM 之前就已绑定(bind)。
删除 $( window ).load(function() {
包装器或将其替换为 DOM 就绪的 $(function() {
并且它会起作用。
关于javascript - 为什么图像不出现在我的文本字段中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20843148/