我的对象newHomes在运行代码时会被删除。它无法从浏览器控制台调用。代码中的console.log
确实会返回值。
$(() => {
console.log($('#zillowLink').attr('href'))
console.log("js is running");
$('#addHome').removeClass('btn-danger').addClass('btn-success');
$('h1').addClass('text-center');
var newHomes = [
{address: "27569 Cedarwood Drive", sf: "2,535", bedrooms: 3, baths: 2.5, price: "$496,500"},
{address: "316 Annandale Drive", sf: "1,326", bedrooms: 4, baths: 2, price: "$275,000"},
{address: "251 Grandview Road", sf: "3,800", bedrooms: 3, baths: 2, price: "$699,900"},
{address: "28571 Manitoba", sf: "2,960", bedrooms: 4, baths: 3.5, price: "$775,000"}
];
console.log(newHomes);
var cells = $('#homes thead tr').children();
cells.eq(0).css('color', 'blue');
cells.eq(4).css('color', 'green');
console.log(newHomes);
const newLink = $( '<br><br><a id="zillowLink" href="http://www.zillow.com">Visit Zillow.com<a>' );
newLink.appendTo('body');
console.log(newHomes);
const addNewHome = ($event) => {
var counter = 0;
$($event.currentTarget).appendTo(newHomes["counter"])
}
console.log(newHomes);
$('#zillowLink').attr( "target", "_blank" ); //_blank opens new Tab
$('#addHome').on('click', 'tr', addNewHome);
const removeHome = ($event) => {
$($event.currentTarget).fadeOut(
500, ()=>{
this.remove
});
}
console.log(newHomes);
$('#homes tbody').on('click', 'tr', removeHome);
console.log(newHomes);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome Back to jQuery</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>
<body class="container">
<h1 class="jumbotron">Lake Arrowhead Homes For Sale</h1>
<table id="homes" class="table">
<thead>
<tr>
<th>Address</th>
<th>Sq. Ft.</th>
<th>Bedrooms</th>
<th>Baths</th>
<th>Price</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>27374 Matterhorn Drive</td>
<td>1,664</td>
<td>3</td>
<td>2</td>
<td>$279,500</td>
<td><button class="btn btn-xs btn-danger">Remove</button></td>
</tr>
<tr>
<td>243 El Dorado</td>
<td>4,900</td>
<td>6</td>
<td>6.5</td>
<td>$990,000</td>
<td><button class="btn btn-xs btn-danger">Remove</button></td>
</tr>
<tr>
<td>1228 Klondike Drive</td>
<td>2,158</td>
<td>4</td>
<td>2.5</td>
<td>$400,000</td>
<td><button class="btn btn-xs btn-danger">Remove</button></td>
</tr>
</tbody>
</table>
<br>
<button id="addHome" class="btn btn-danger">Add Home</button>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="js/app.js"></script>
</body>
</html>
&#13;
答案 0 :(得分:0)
您将无法从控制台级别访问newHomes
变量,因为它是在您的immiediately-invoked函数的本地范围内定义的。这意味着newHomes
在函数的上下文中有效,但它不存在于函数的外部。你需要暴露它。例如:
var foo = function() {
this.a = 1;
var b = 2;
}
如果您将此代码粘贴到浏览器的控制台中并执行foo()
,则访问a
会给您1
,但访问b
会导致ReferenceError: b is not defined
答案 1 :(得分:0)
将您的变量拉出IIFE。因此,将 var newHomes 拉出您的函数并将其放在函数上方。在外面进行更改可以在函数外部访问它。