2012-10-04 25 views
0

嘿我试图下面让我的jQuery代码的工作:jQuery的追加与图像的HTML然后将其删除不显示

function submitContactUs() { 
    if ($('#cf-name-txt').val() == '' || $('#cf-name-txt').val().charAt(0) == '*') { 
     $('#cf-name-txt').append("<img src=\"img/attention.png\" width=\"16\" height=\"16\" style=\"position:absolute; left: -7px; top: 7px;\" />"); 
    }  
} 

和HTML代码是这样的:

<div id="contactus-name"> 
    <input type="text" id="cf-name-txt" style="width: 200px;" class="formBoxesContact" value="*Your Name"> 
</div> 

它将图像添加到上面的html代码的末尾,但它不显示?它看起来像这样的萤火:

firebug

我在做什么,以使其不显示?

回答

1

试试这个

$('#cf-name-txt').after("<img src=\"img/attention.png\" width=\"16\" height=\"16\" style=\"position:absolute; left: -7px; top: 7px;\" />"); 

OR

$("<img src=\"img/attention.png\" width=\"16\" height=\"16\" style=\"position:absolute; left: -7px; top: 7px;\" />").insertAfter($('#cf-name-txt')); 

您试图追加图像输入..尝试输入标签后追加..

.after()应该工作

编辑

if(!$('#cf-name-txt').next('img').length) 
$('#cf-name-txt').after("<img src=\"img/attention.png\" width=\"16\" height=\"16\" style=\"position:absolute; left: -7px; top: 7px;\" />");​ 

FIDDLE

+0

真棒......它让我如何停止生成图像每次我按下按钮时提交...? – StealthRT

+0

添加一个if条件来检查图像,然后添加它..检查编辑 –

+0

这似乎并不工作...无论如何保持添加 – StealthRT

1

您正在尝试在输入内显示图像。尝试使用样式化的可编辑div或其他东西。

1

你可能要插入的图像后的输入,而不是里面的吧。 为此,请使用jQuery的after函数,而不是append

作为一种替代方法,您可以使用CSS类在输入旁边添加图像,并将嵌入的HTML替换为您的javascript。

在你的CSS:

input.attention:after { 
    content: url('img/attention.png'); 
} 

然后,在JavaScript的:

function submitContactUs() { 
    if ($('#cf-name-txt').val() == '' || $('#cf-name-txt').val().charAt(0) == '*') { 
     $('#cf-name-txt').addClass("attention"); 
    }  
} 
+0

但是img已经有一个类已经分配给它了? – StealthRT

+0

在这种情况下,没有'img'元素,图像显示在输入的[':: after'伪元素](https://developer.mozilla.org/en-US/docs/CSS/::after ) –

1

好像(从图片的名字),你基本上是想表现出 “关注” 的形象当表格被提交并且一个字段没有被输入时。

正如其他帖子所说,您不能在<input>标签内放置图像,但这并不意味着您不能在标签内出现图像。

要做到这一点的方法是设置inputbackground风格。所以要用jQuery来做到这一点,请使用;

$('#cf-name-txt').addClass('alert-icon'); 

然后让CSS

input.alert-icon{ background: url(img/attention.png) no-repeat right center; } 

然后,您可以发挥一下与造型,也删除类,当用户将焦点设置到输入。

1

输入字段不能包含元素(以及几乎任何东西)。 使用$('#cf-name-txt')。before(“”);添加图像和(“#cf-name-txt-img”)。remove()将其删除。

甚至更​​好,把图像中的HTML与样式display:none和打开它转变作风中显示:块

<div id="contactus-name"> 
    <img src="img/attention.png" id="cf-name-txt-img" width="16" height="16" style="position:absolute; left: -7px; top: 7px; display:none" /> 
    <input type="text" id="cf-name-txt" style="width: 200px;" class="formBoxesContact" value="*Your Name"> 
    </div> 

并使用$(“#CF-名-TXT-IMG “).show()显示它,$(”#cf-name-txt-img“)。hide()将其删除。

你的情况:

function submitContactUs() { 
    var $img = $("#cf-name-txt-img"); 
    if ($('#cf-name-txt').val() == '' || $('#cf-name-txt').val().charAt(0) == '*') { 
     $img.show(); 
    } else { 
     $img.hide(); 
    } 

} 
+0

我将有多个需要该图标的输入框。我只是想把它附加到任何需要它的盒子上,当他们尝试提交表单时,他们会留下一些东西。真的不想手动把img放在每个输入标签旁边... – StealthRT