我正在尝试使用脚本标记从 HTML 文件调用一个 javascript 文件(该文件是一个数组),并且我想调用该数组上的属性。
editor.service('pk7Data', function () {
this.pokemonList = [
{
index: 0,
pokedex: 0,
name: 'None'
},
{
index: 1,
pokedex: 1,
name: 'Bulbasaur'
},
{
index: 2,
pokedex: 2,
name: 'Ivysaur'
},
{
index: 3,
pokedex: 3,
name: 'Venusaur'
}
我想从 HTML 脚本调用 name
属性。我该怎么做?
最佳答案
您正在寻找这样的东西吗? 更新了 JSFiddle
https://jsfiddle.net/qtjr6oqc/
$(document).ready(function() {
//console.log(externalFunc.getPokemonList());
$.each(externalFunc.getPokemonList(), function(k, v) {
$('#list').append('<option value="' + v.name + '">' + v.name + '</option>');
});
$('#list').on('change', function(e) {
var name = $(this).val();
if (name === "None") {
$('#name').text("");
$('#img').attr('src', "");
return;
}
var pokeObj = externalFunc.getPokemonByName(name);
if(typeof pokeObj == "object") {
$('#name').text(pokeObj.name);
$('#img').attr('src', pokeObj.img);
}
});
});
//
//alert(JSON.stringify(externalFunc.getPokemonByName("Bulbasaur")));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
// PUT THIS CODE IN AN EXTERNAL JS file and
// and add the source in the html like:
// <script type="text/javascript" src="external.js">
var externalFunc = (function() {
var list_ = [{
"index": 0,
"pokedex": 0,
"name": "None"
}, {
"index": 1,
"pokedex": 1,
"name": "Bulbasaur",
"img": "https://s-media-cache-ak0.pinimg.com/originals/96/d2/1d/96d21d738561947f96255e6f12f1754a.png"
}, {
"index": 2,
"pokedex": 2,
"name": "Ivysaur",
"img": "http://cartoonbros.com/wp-content/uploads/2016/11/Ivysaur-1.gif"
}, {
"index": 3,
"pokedex": 3,
"name": "Venusaur",
"img": "http://vignette2.wikia.nocookie.net/pokemon/images/b/b2/003Venusaur_Dream.png/revision/latest?cb=20140908150056"
}];
var getPokemonByName = function(name) {
if (name == null) {
return "";
}
for (var i = 0; i < list_.length; i++) {
var pokeObj = list_[i];
if (pokeObj.name === name) {
return pokeObj;
}
}
return "";
};
var getPokemonList = function() {
return list_;
};
var obj = {
getPokemonByName: getPokemonByName,
getPokemonList: getPokemonList
};
return obj;
})();
</script>
<select name="list" id="list">
</select>
<p>
<span id="name"></span><br/>
<span id="pic"><img src="" id="img" style="width:50px;height:50px;border:0px;"/></span>
</p>
关于javascript - 如何从另一个文件调用数组的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43922860/