简体   繁体   English

使用jQuery将图像添加到div

[英]Add an image to a div using jquery

I have a sticky menu/floater bar when a user scrolls down on the page ... using jQuery I add the floater-bar class to the #menu-wrapper. 当用户向下滚动页面时,我有一个粘滞的菜单/浮动栏...使用jQuery,我将floater-bar类添加到#menu-wrapper中。

My goal is to add an image within an anchor at the same time floater-bar class is added so that the logo is on the floater bar as well. 我的目标是在添加浮动框的同时添加锚点中的图像,以便徽标也位于浮动框上。

if ($(window).scrollTop() > $header_top_pos) {
  $("#menu-wrapper").addClass("floater-bar");
} else {
  $("#menu-wrapper").removeClass("floater-bar");
}

I have tried the following: 我尝试了以下方法:

$("#menu-wrapper").append("<a href="#"><img src="image" /></a>");

Tried .add and .prepend as well 也尝试过.add和.prepend

It makes the whole script fail as the floater-bar class no longer gets added into the menu. 由于不再将float-bar类添加到菜单中,因此使整个脚本失败。

Do this instead: 改为这样做:

$("#menu-wrapper").append("<a href='#'><img src='image' /></a>");

You're using " to start and end the append , but then using it also to assign a href and the src , which is canceling out the string. 您正在使用"来开始和结束append ,但是随后还使用它来分配hrefsrc ,从而取消了字符串。

So only use " to start and end it, and if you need quotes inside, use ' , or escape the double quotes by using \\" . 因此,只能使用"开始和结束它,如果您需要在其中使用引号,请使用' ,或者使用\\"转义双引号。”

If you wanted to do string concatenation (although not what you asked for, could come in handy later on), you do something like this: 如果您想进行字符串连接(尽管不是您想要的,以后可以派上用场),您可以执行以下操作:

$("#menu-wrapper").append("<a href='"+url+"'><img src='"+image+"' /></a>");

image and url would be variables. imageurl将是变量。 + is used to concatenate the string, giving you access to use variables within the string. +用于连接字符串,使您可以访问字符串中的使用变量。

try this 尝试这个

var anchor = $("a").attr("href","#");
var img = $("img").attr("src","img_source");
anchor.append(img);
$("#menu-wrapper").append(anchor);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM