[英]How to add HTML tags into attribute with jQuery
I need to set some HTML code with jQuery to html attribute. 我需要使用jQuery将一些HTML代码设置为html属性。
Something like this : 像这样的东西:
$(".carousel").attr("data-dot","<button role="button" class="owl-dot"><?php
include("inc/chart3.svg")?></button>");
but there is problem with escaping... How can i solve this problem? 但是转义有问题...我该如何解决这个问题?
Here's an extensive breakdown of all your options. 这是您所有选项的详细分类。
Both double and single quotes can be escaped with backslashes: 双引号和单引号都可以使用反斜杠转义:
$(".carousel").attr("data-dot", "<button role=\"button\">");
$(".carousel").attr("data-dot", '<button role=\'button\'>');
Of course, you can also use single quotes inside of double quotes depending on the scenario (ie, yours): 当然,您也可以根据情况(即您的情况)在双引号内使用单引号:
$(".carousel").attr("data-dot", "<button role='button'>");
Finally, single quotes can also be placed inside double quotes: 最后,单引号也可以放在双引号内:
$(".carousel").attr("data-dot", '<button role="button">');
EDIT 编辑
A good way to play around with escaping strings is just plugging stuff into your browser console. 解决转义字符串的一种好方法是将内容插入浏览器控制台。
console.log("Here is a \\"quote.\\""); console.log('Here is a "quote."'); console.log("Here is 'another quote.'"); console.log('Here is yet \\'another quote.\\'');
Tidier if you did something like this: 如果您做过这样的事情,请采取以下措施:
let $btn = $("<button/>", { "role": "button", "class": "owl-dot", "html": "<?php include('inc/chart3.svg');?>" }); $(".carousel").attr("data-dot", $btn.prop('outerHTML')); console.log('carousel: ', $('.carousel').attr('data-dot'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="carousel"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.