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('<div ></div>');
banner = pdpHead.find(".bannerLink");
}
}
if(banner.length!=0){
banner.append("<a href='#' onclick='alert('hi')'><img src='https://test.com' style='margin-top:5px;' ></a>");
$('.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
thelink
astext
nothtml
Second, you need to skip the nested
"
double quote inside thealert
$(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('<div ></div>');
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("hi")'
for escaping "
Code:
banner.append("<a href='#' onclick='alert("hi")'><img src='https://test.com' style='margin-top:5px;' ></a>");
Edit: I changed <
and >
to <
and >
so that the element will not be appended as text