我尝试使用dart创建一个程序来保存html文件中的联系人。
这是我在dart中的代码:
import 'dart:html';
void saveContact() {
Storage localStorage = window.localStorage;
var txtFirst = query("#firstname");
String first = txtFirst.text;
var txtLast = query("#lastname");
String last = txtLast.text;
var txtEmail = query("#email");
String email = txtEmail.text;
var txtMobile = query("#mobile");
String mobile = txtMobile.text;
var txtHome = query("#home");
String home = txtHome.text;
var txtOffice = query("#office");
String office = txtOffice.text;
var contact = {
"firstname" : first,
"lastname" : last,
"email" : email,
"mobile" : mobile,
"home" : home,
"office" : office
};
localStorage.setItem(first + " " + last, JSON.stringify(contact));
var test2 = JSON.parse(localStorage.getItem(first + " " + last));
var result = query("#divContents");
result.text = test2.tostring();
}
void main() {
querySelector('#savecontacts').onClick.listen(saveContact);
}
我想在其中一个div中输出联系人,看看dart代码是否有效。但没有任何反应......请帮忙。
答案 0 :(得分:1)
这应该做你想要的:
import 'dart:html';
import 'dart:convert' show JSON;
void saveContact() {
Storage localStorage = window.localStorage;
// (... as InputElement) isn't actually necessary,
// it's just to silence the analyzer
var first = (querySelector("#firstname") as InputElement).value;
var last = (querySelector("#lastname") as InputElement).value;
var email = (querySelector("#email") as InputElement).value;
var mobile = (querySelector("#mobile") as InputElement).value;
var home = (querySelector("#home") as InputElement).value;
var office = (querySelector("#office") as InputElement).value;
var contact = {
"firstname" : first,
"lastname" : last,
"email" : email,
"mobile" : mobile,
"home" : home,
"office" : office
};
localStorage['$first $last'] = JSON.encode(contact);
var test2 = JSON.decode(localStorage['$first $last']);
var result = querySelector("#divContents");
result.text = test2.toString();
}
void main() {
querySelector('#savecontacts').onClick.listen((_) {
saveContact();
print('saved');
});
}
我用于此示例的 HTML
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="application/dart" src="index.dart"></script>
<!-- for this next line to work, your pubspec.yaml file must have a dependency on 'browser' -->
<script src="packages/browser/dart.js"></script>
<input id="firstname">
<input id="lastname">
<input id="email">
<input id="mobile">
<input id="home">
<input id="office">
<button id="savecontacts">save</button>
<div>
<b>result</b>
<div id="divContents"></div>
</div>
</body>
</html>