Home > OS >  Attaching onclick on JQUERY
Attaching onclick on JQUERY

Time:08-16

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 &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'});
                    }
                }
    });

CodePudding user response:

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 &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 ></div>

CodePudding user response:

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

  • Related