JS,用于替换页面中的字符串


JS for string replacement in a page

我的代码中出现了以下HTML

<div id="optinforms-form1-name-field-container"> <input id="optinforms-form1-name-field" name="FNAME" placeholder="Vaše meno" style="font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#666666" type="text"></div>

我想要一个js,它可以首先检查当前页面,如果访问了所需的页面,那么它会将上面代码中的字符串"Vaše meno"替换为"Your Name"。我已经尝试了以下代码,但由于我是js的新手,我无法使其工作。我正在研究wordpress框架。

var sPath = window.location.pathname;
var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
if(sPage == "index.php"){      
$("optinforms-form1-name-field").each(function() {
var text = $(this).text();
text = text.replace("Vaše meno", "Your Name");
$(this).text(text);});}

ID选择器以"#"开头,您应该替换占位符的值,而不是文本。在jQuery中:

if (/index'.php$/i.test(window.location.pathname)) {
  $('#optinforms-form1-name-field')[0].placeholder = 'Your name';
  // or
  //   $('#optinforms-form1-name-field').prop('placeholder','Your name');
}

或纯JS:

if (/index'.php$/i.test(window.location.pathname)) {
  document.getElementById('optinforms-form1-name-field').placeholder = 'Your name';
}