用javascript解释image.src.match

use*_*762 6 html javascript image match toggle

我正在学习本教程,发现一些javascript代码难以理解.

链接到教程

http://www.w3schools.com/js/tryit.asp?filename=tryjs_lightbulb

我需要澄清代码

<script>
function changeImage() {
    var image = document.getElementById('myImage');
    if (image.src.match("bulbon")) {
        image.src = "pic_bulboff.gif";
    } else {
        image.src = "pic_bulbon.gif";
    }
}
</script>
Run Code Online (Sandbox Code Playgroud)

我不明白MATCH(在image.src.match中)实际意味着什么.它是否具有切换动作的东西.我找不到任何有用的文章.

Jan*_*iak 7

.match() 测试以查看给定字符串是否与正则表达式匹配.

在您的示例中,它测试是否image.src包含字符串"bulbon".

如果匹配,则更image.src改为"pic_bulboff.gif"

有关此功能的更多信息,我建议:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match


Mau*_*ähä 7

那么,@elclanrs已经提供了一个链接String.prototype.match()解释.但是,下面是一个为您澄清一些事情的答案.

HTML:

<img id="myImage" src="http://www.w3schools.com/js/pic_bulbon.gif" />
Run Code Online (Sandbox Code Playgroud)

JavaScript的:

// capture the image
var image = document.getElementById('myImage');

console.log(image.src);                                // http://www.w3schools.com/js/pic_bulbon.gif
console.log(image.src.match("word-not-in-src-name"));  // null
console.log(image.src.match("bulbon"));                // ["bulbon", index: 32, input: "http://www.w3schools.com/js/pic_bulbon.gif"] 

// image.src.match("bulbon") will return an Array, but it evaluates true in JavaScript
// This is the reason why "Evaluates true!" is printed out to console
if(image.src.match("bulbon")) {
    console.log("Evaluates true!");
}

// To prove my point, "Empty array!" also will be printed out to console
if([]) {
    console.log("Empty array!");
}
Run Code Online (Sandbox Code Playgroud)

您可以通过以下JS FIDDLE EXAMPLE自己看到这一点

因此,要返回代码示例:

if (image.src.match("bulbon")) {
    image.src = "pic_bulboff.gif";
} else {
    image.src = "pic_bulbon.gif";
}
Run Code Online (Sandbox Code Playgroud)

..意思是如果bulbon word在当前图像src属性中,则图像将被更改为pic_bulboff.gif因为执行将在if块内移动,因为image.src.match("bulbon")将返回一个数组,(如上面的示例所示,并在文档中进行了解释) .

干杯,希望你现在明白如何检查某些单词是否是未来字符串的一部分:)