怎么用JS读写本地文本文件

JavaScript012

怎么用JS读写本地文本文件,第1张

采用jquery的ajax方式进行文件信息读取

代码

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

<html>

<head>

<script type="text/javascript" src="/jquery/jquery.js"></script>

<script type="text/javascript">

$(document).ready(function(){

$("#b01").click(function(){

htmlobj=$.ajax({url:"/jquery/test1.txt",async:false})

$("#myDiv").html(htmlobj.responseText)

})

})

</script>

</head>

<body>

<div id="myDiv"><h2>通过 AJAX 改变文本</h2></div>

<button id="b01" type="button">改变内容</button>

</body>

</html>

const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?'

console.log(p.replace('dog', 'monkey'))

// expected output: "The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?"

const regex = /Dog/i

console.log(p.replace(regex, 'ferret'))

// expected output: "The quick brown fox jumps over the lazy ferret. If the dog reacted, was it really lazy?"

首先,只能取出inline的JS内容,如果脚本是通过 src 加载进来的,这个是没办法取出的。

对于 inline 的 JS 内容,高端浏览器使用 textContent ,IE6/7/8 使用 innerText。下面是例子:

<script id="s1">alert(1)</script>

var script = document.getElementById( 's1' )

var text = script.textContent || script.innerText

console.log( text )// output alert(1)