通过JavaScript插入HTML时更改文件路径

时间:2015-10-07 12:55:16

标签: javascript html

我有一个运行批处理文件的按钮,代码为:

<button onclick="window.open('file:///C:/Users/gthornbu/Desktop/TEST/test.bat')">Continue</button>

我可以将它直接放在HTML文件中并且它可以正常工作,但是我通过output.innerHTML将这段特定代码插入到文件中并且它无法正常工作。我假设&#34; /&#34;必须改变,但我也尝试过:

<button onclick='window.open('file:///C:\\Users\\gthornbu\\Desktop\\TEST\\test.bat')'>Continue</button>...which also does not work. Any ideas what I'm missing here?

我正在使用的JavaScript:

function novpn() {
  var output = document.getElementById("main");
  var sentence = "<h3>You are not connected to the VPN. In order to proceed, you must sign in and launch 'Network Connect'.</h3></br><button onclick='window.open('file:///C:\\Users\\gthornbu\\Desktop\\TEST\\test.bat')'>Continue</button>";

  output.innerHTML = sentence;
}

3 个答案:

答案 0 :(得分:3)

您可以使用'字符声明字符串。如果您必须使用html属性中的参数调用函数,声明可能会成为问题。

您可以使用转义字符解决此问题。 \

它将逃脱表现所造成的角色。你必须在它之前添加。

var str = "string";
var str2 = \""string\"";

str === str2 // true

在你的情况下,你可以这样做。

output.innerHTML = '<button onclick="window.open(\'file:///C:/Users/gthornbu/Desktop/TEST/test.bat\')">Continue</button>'

工作JS小提琴

http://jsfiddle.net/ebilgin/wLe04pwg/

答案 1 :(得分:3)

'嵌套在'内。

简单的方法是使用",但作为内部引用进行转义。然后返回原始URL(使用正斜杠):

var sentence = "<h3>You are not connected to the VPN. In order to proceed, you must sign in and launch 'Network Connect'.</h3></br>" +
    "<button onclick='window.open(\"file:///C:/Users/gthornbu/Desktop/TEST/test.bat\")'>Continue</button>";

答案 2 :(得分:0)

将html标记和javascript代码嵌套在字符串中可能会让单引号和双引号成为正确的问题并在需要时转义。虽然它允许一些相当快速的应用程序开发,如果你需要稍后维护它,你可以试试这个解决方案。

而不是弄清楚哪些引号需要去我在vanilla javascript命令中重新创建目标html,以通过使用不同的函数创建相同的结果并将它们连接在一起。

我使用document.createElement函数创建所需的html元素,并使用appendChild函数将它们添加到主元素。该按钮具有打开附加到onclick事件的窗口的功能。

function novpn() {
  var output = document.getElementById("main");
  
  // create the h3 elelement and its content
  var h3 = document.createElement('h3');
  h3.innerHTML = "You are not connected to the VPN. In order to proceed, you must sign in and launch &apos;Network Connect&apos;.";
  
  // the br
  var br = document.createElement('br');
  
  // create the button
  var button = document.createElement('button');
  button.innerHTML = "Continue";
  // the onclick handler can now become
  // a normal javascript function
  button.onclick = function() {
    window.open('file:///C:/Users/gthornbu/Desktop/TEST/test.bat');
  };
  
  // add all created elements to main
  output.appendChild(h3);
  output.appendChild(br);
  output.appendChild(button);
}

// start
novpn();
<div id='main'>
  <div>title</div>
</div>