简体   繁体   中英

HTML Tag containing quotes inside JavaScript code with quotes

I am writing JavaScript code that on click assigns the function getImage the source of the image that is later supposed to be display in the page. However, the quotation marks are giving me a problem.

<img src="bill.jpg" class="captify" 
id="teamformat" alt="Bill Gates" onclick="getName('Bill Gates'); 
getMotto('Bill\'s motto'); 
getImage ('<img src=\"http://www.somepage.com/images/team/bill.jpg\"/>');" />

How would I fix the quotation marks in the getImage function? Thank you.

Normally, you don't need to escape double quotes in single quote delimited strings:

getImage ('<img src="http://www.somepage.com/images/team/bill.jpg"/>');" />

Similarly, getMotto can be re-written as:

getMotto("Bill's motto"); 

You are getting a problem because you are using both style of quotes within a single attribute - you have way too much JavaScript there and you do need to escape the inner double quotes (using &quot; ).

Both of these should be placed within a javascript function that you attach the click event to - don't directly place them in the onclick event handler, it is bad practice.

Something like:

function getDetailsForBill(){
     getName('Bill Gates'); 
     getMotto('Bill\'s motto'); 
     getImage ('<img src="http://www.somepage.com/images/team/bill.jpg" />');
}

Making the onclick :

onclick="getDetailsForBill();"

Though you really should be registering an event listener, using addEventListener .

不要逃避它:

getImage ('<img src="http://www.somepage.com/images/team/bill.jpg"/>');" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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