如何使用 JavaScript 设置嵌入式引号的引号类型?
在本教程中,我们将学习如何使用 JavaScript 设置嵌入式引号的引号类型。
可以使用 JavaScript 更改引号类型。例如,如果一个句子在双引号("")中,则可以将其修改为单引号("'"。要设置引号,请使用 元素。使用 quotes 属性添加引号类型。
使用 quotes 属性设置引号类型
在 JavaScript 中,quotes 属性用于设置嵌入式引号的引号类型。可以使用引号字符或 HTML 条目编号设置引号。也可以使用此属性设置第一级引号以及第二级引号。它是元素对象的样式属性的一部分,因此我们还需要 document.getElementById() 方法来访问元素对象。
语法
document.getElementById('id').style.quotes = string string string string | none | inherit | initial
在上面的语法中,我们使用 quotes 属性来设置嵌入引号的引号类型。document.getElementById() 方法访问 id 为"id"的元素的元素对象。
参数
string string string string − 它指定引号。前两个字符串用于第一级引文,后两个字符串用于第二级引文。
none − 不指定引号。
inherit − 引号由其父元素继承。
initial − 引号设置为默认值。
示例
在下面的示例中,我们通过单击按钮设置多个引文的引号类型。按钮"设置引号类型"与单击事件相关联,每当用户单击按钮时,该事件都会触发函数"setQuotation()"。
<html> <head> <style> .item { padding: 15px; margin-top: 5px; background-color: aliceblue; border: 1px solid black; } </style> </head> <body> <h2> Set the type of quotation marks for embedded quotations using the <i> quotes property </i> with JavaScript </h2> <button onclick="setQuotation()"> Set Quotation Type </button> <div class="item"> <q id="q1"> Hello World! </q> </div> <div class="item"> <q id="q2"> Welcome <q> User </q> to Tutorialspoint </q> </div> <script> // "Set Quotation Type" button click event handler function function setQuotation() { const q1 = document.getElementById("q1") const q2 = document.getElementById("q2") q1.style.quotes = "'\253' '\273'" q2.style.quotes = "'`' '`' '<' '>'" } </script> </body> </html>
使用 setProperty 方法设置引号的类型
JavaScript 中的 setProperty 方法用于设置元素的任何新属性或现有属性。此方法在元素的元素对象的 style 属性中可用。它采用参数中的属性名称和值,并使用提供的值设置该属性。例如,要设置嵌入引号的引号类型,setProperty 方法将"quotes"作为第一个参数,在第二个参数中,它采用值。
语法
document.getElementById('id').style.setProperty(name, value, priority)
在上述语法中,document.getElementById() 方法返回元素的元素对象,以便我们可以对其执行 setProperty 方法。
参数
name − 属性的名称。
value − 属性值。
priority − 属性值的优先级(可选)。
示例
在下面的示例中,我们使用 setProperty 方法用 JavaScript 设置了嵌入引号的引号类型。用户可以在输入字段中输入内容。使用"设置引号类型"按钮,在单击事件上执行"setQuotationType()"函数,并根据用户输入设置引号。
<html> <body> <h2> Set the type of quotation marks for embedded quotations using the <i> setProperty method </i> with JavaScript </h2> <h4> Enter the type of quotation marks: </h4> <input type="text" id="quotation-type" name="quotation-type"> <button onclick="setQuotation()"> Set Quotation Type </button> <div style="padding: 15px; margin-top: 5px; background-color: aliceblue; border: 1px solid black;"> <q id="q"> Welcome <q> User </q> to Tutorialspoint</q> </div> <p> Note : Please enter the type of quotation mark with double quotes such as ("< " ">") </p> <script> // 'Set Quotation Type' button click event handler function function setQuotation() { const q = document.getElementById('q') // user input value for quotation marks const quotation_type = document.getElementById('quotation-type').value; q.style.setProperty('quotes', quotation_type); } </script> </body> </html>
在本教程中,我们学习了如何使用 JavaScript 设置嵌入引号的引号类型。我们还学习了如何获取用户输入值并设置引号。此外,我们还学习了 quotes 属性和 setProperty 方法。用户可以根据自己的需求使用其中任何一种。