[英]How to add HTML tags into attribute with jQuery
我需要使用jQuery將一些HTML代碼設置為html屬性。
像這樣的東西:
$(".carousel").attr("data-dot","<button role="button" class="owl-dot"><?php
include("inc/chart3.svg")?></button>");
但是轉義有問題...我該如何解決這個問題?
這是您所有選項的詳細分類。
雙引號和單引號都可以使用反斜杠轉義:
$(".carousel").attr("data-dot", "<button role=\"button\">");
$(".carousel").attr("data-dot", '<button role=\'button\'>');
當然,您也可以根據情況(即您的情況)在雙引號內使用單引號:
$(".carousel").attr("data-dot", "<button role='button'>");
最后,單引號也可以放在雙引號內:
$(".carousel").attr("data-dot", '<button role="button">');
編輯
解決轉義字符串的一種好方法是將內容插入瀏覽器控制台。
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.\\'');
如果您做過這樣的事情,請采取以下措施:
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.