简体   繁体   English

如何 append 图像和锚标签

[英]How to append image and anchor tag

I am writing a function where I dynamically create various divs, containing an image and an anchor tag and then append them to an existing div.我正在编写一个 function ,我在其中动态创建各种 div,包含图像和锚标记,然后将 append 它们添加到现有 div。 Now, they're being appended alright, the problem, is that something is wrong with both the images and the anchor tags.现在,它们被附加了,问题是图像和锚标签都有问题。

The anchors cannot be clicked on.无法点击锚点。 They are just showing as blue text, not a link.它们只是显示为蓝色文本,而不是链接。 And the image is not being displayed.并且没有显示图像。 The latter can't be caused because of incorrect file path.后者不可能是因为文件路径不正确造成的。

在此处输入图像描述

Here is the Javascript/JQuery part:这是 Javascript/JQuery 部分:

 $.ajax({
          
            url: 'Home/GetComments',
            data: { postId: id },
            dataType: 'json',
            cache: false,
            success: function (result) {
                for (var i = 0; i < result.length; i++) {
                    var div = document.createElement("Div");
                    div.setAttribute('class', 'comment');

                    var image = document.createElement("img");
                    var imageSource = "~/images/" + result[i].userImage;
                    image.src = imageSource;
                    div.appendChild(image);

                    var a = document.createElement('a');
                    var linkText = document.createTextNode(result[i].userName);
                    a.appendChild(linkText);
                    a.setAttribute('asp-action', 'UserProfile');
                    a.setAttribute('asp-route-name', result[i].userName);
                    
                    div.appendChild(a);

                    $("#" + stringId).append(div);
                }      },
        });

And this is the response from the controller:这是来自 controller 的响应:

 public JsonResult GetComments(long postId)
        {
            var comment1 = new Comment()
            {      
                Id = 1,
                UserName = "User1",
                UserImage = "Udklipre.PNG"          
            };
            var comment2 = new Comment()
            {
                Id = 2,
                UserName = "User2",
                UserImage = "Udklipre.PNG"
            };

            Comment[] comments = { comment1, comment2 };
            return Json(comments);
        }

Anchor tags need a hyperlink reference ( href ) in order for the browser to understand them as clickable, which is why you see href="#" so frequently.锚标签需要一个超链接引用( href ),以便浏览器将它们理解为可点击,这就是为什么您经常看到href="#"的原因。 If you don't want the hash in the url when you click on it, you can use href="javascript: void(0)" instead.如果您在单击时不希望 url 中的 hash 出现,则可以使用href="javascript: void(0)"代替。

a.setAttribute('href', '#');

You must add the 'href' attribute to make it look clickable.您必须添加“href”属性以使其看起来可点击。 Here you have two options:在这里,您有两个选择:

a.href = 'javascript:void(0)';
// or
a.setAttribute('href', 'javascript:void(0)');

Here is a worked demo(tag-helper such as asp-action cannot be used in ajax):这是一个有效的演示(无法在 ajax 中使用诸如asp-action之类的标签助手):

HomeController:家庭控制器:

public IActionResult Add() {
            return View();
        }
        public JsonResult GetComments(long postId) {
            var comment1 = new Comment()
            {
                Id = 1,
                UserName = "User1",
                UserImage = "gif.gif"
            };
            var comment2 = new Comment()
            {
                Id = 2,
                UserName = "User2",
                UserImage = "t-shirt.jpg"
            };

            Comment[] comments = { comment1, comment2 };
            return Json(comments);
        }
        public ActionResult UserProfile(string username) {
            return View("Add");
        }

Add.cshtml:添加.cshtml:

 <button onclick="add()">add</button>
<div id="stringId"></div>
@section scripts {
    <script type="text/javascript">
        function add() {
            $.ajax({

                url: 'GetComments',
                data: { postId: 1 },
                dataType: 'json',
                cache: false,
                success: function (result) {
                    for (var i = 0; i < result.length; i++) {
                        var div = document.createElement("Div");
                        div.setAttribute('class', 'comment');
                        var image = document.createElement("img");
                        var imageSource = "/images/" + result[i].userImage;
                        image.src = imageSource;
                        div.appendChild(image);

                        var a = document.createElement('a');
                        var linkText = document.createTextNode(result[i].userName);
                        a.appendChild(linkText);
                        a.href = "UserProfile?username=" + result[i].userName;
                        div.appendChild(a);

                        $("#stringId").append(div);
                    }
                },
            });
        }
    </script>

}

result:结果: 在此处输入图像描述

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

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