skip to Main Content

I have a problem since I wanted to attach the onclick alert function on an <a/> tag.
This thing doesn’t work. The alert('hi') doesn’t appear. Did I miss something?

    $(document).ready(function(){
        const requiredBy = true;
                if(requiredBy){
                    var banner = $(".bannerLink");
                    if(banner.length==0){
                        var pdpHead = $("[replaceclass='PDPHeadReplace']");
                        if(pdpHead.length!=0){
                            pdpHead.prepend('&lt;div class="bannerLink"&gt;&lt;/div&gt;');
                            banner = pdpHead.find(".bannerLink");
                        }
                    }
                    if(banner.length!=0){
                        banner.append("&lt;a href='#' onclick='alert('hi')'&gt;&lt;img src='https://test.com' style='margin-top:5px;' &gt;&lt;/a&gt;");
                        $('.helloDiv').css({ 'display' : 'block', 'padding-top': '1rem'});
                    }
                }
    });

2

Answers


  1. You can use onclick='alert(&quot;hi&quot;)' for escaping "

    Code:

    banner.append("<a href='#' onclick='alert(&quot;hi&quot;)'><img src='https://test.com' style='margin-top:5px;' ></a>");
    

    Edit: I changed &lt; and &gt; to < and > so that the element will not be appended as text

    Login or Signup to reply.
  2. There are two issues here.

    • First, you haven’t skip the special characters to not append the link as text not html

    • Second, you need to skip the nested " double quote inside the alert

        $(document).ready(function(){
            const requiredBy = true;
                    if(requiredBy){
                        var banner = $(".bannerLink");
                        if(banner.length==0){
                            var pdpHead = $("[replaceclass='PDPHeadReplace']");
                            if(pdpHead.length!=0){
                                pdpHead.prepend('&lt;div class="bannerLink"&gt;&lt;/div&gt;');
                                banner = pdpHead.find(".bannerLink");
                            }
                        }
                        if(banner.length!=0){
                            banner.append("<a href='#' onclick='alert("hi")'>link<img src='https://test.com' style='margin-top:5px;' </a>");
                            $('.helloDiv').css({ 'display' : 'block', 'padding-top': '1rem'});
                        }
                    }
        });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div class="bannerLink"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search