我已经浏览了很多线程,搜索过很多并试图自己解决这个问题,但我不能。我试图解决我的问题。
我收到存储在本地存储中的字符串。
private func addTapRecognizer(toView view: UIView) {
let recognizer = UITapGestureRecognizer(target: self, action: #selector(didTapButton(sender:)))
view.isUserInteractionEnabled = true
view.addGestureRecognizer(recognizer)
}
@objc private func didTapButton(sender: UIGestureRecognizer) {
guard let view = sender.view else {
return
}
switch view {
case self.imageView: // any view you want to check
default:
print(sender.debugDescription)
}
}
然后我将此值传递给构造函数,以将此值赋给对象的属性。这是类和构造函数。
.proporcion-fija-indice {
display: block;
margin: 0;
padding-top: 48.30%; /* 2026px/4194px = 0.4830 */
background-image: url('../img/portada.jpg');
background-size: cover;
background-position: center center;
margin-top:-50px;
}
#menu .container-fluid {
background-image: url('../img/header.png');
min-height: 150px;
}
在按钮的帮助下,我点击以下功能调用以下功能:
var c = localStorage.getItem('item');
document.write(c)只是测试是否存储了任何值,是的,我的测试'字符串存储。结果,我得到:
undefinedTest
我是JavaScript的新手,我知道不知何故,dataSet对象没有获得值并且没有分配它,但我不知道如何解决它。我真的在stackoverflow上读取了这个主题的每个现有线程,但是无法提出解决方案。谢谢你的时间。
答案 0 :(得分:6)
您的错误在构造函数中!
您错过了_
应该是this._item = item;
而不是this.item = item;
因此你的吸气剂,即:
get item() {
return this._item;
}
返回undefined,因为没有_item
属性...
答案 1 :(得分:1)
正如之前有人对您发表评论,这里的问题是因为您在构造函数中缺少_。但如果这不能解决您的问题,可能问题与localStorage中项目的值有关。这里有一个使用简单字符串的代码示例:
var c = 'hello world';
class dataSet {
constructor (item) {
this._item = item;
}
get item () {
return this._item;
}
}
function buildSet() {
var currentSet = new dataSet(c);
alert(currentSet.item);
alert(c);
}
<!DOCTYPE html>
<html>
<body>
<button onclick="buildSet()">click me</button>
</body>
</html>
答案 2 :(得分:0)
让我们做一些检查并查看代码的行为,因为它按预期工作,唯一的是你缺少一些检查和一些字符。
//make sure that C has a value, maybe it is undefined from here.
var c = "fakeItem";
// also lets do a test with an undefined value.
var d;
class dataSet {
constructor(item) {
this._item = item;
}
get item() {
//you were missing a _ here.
return this._item;
}
}
function buildSet() {
var currentSet = new dataSet(c); //this works because C is defined
var dSet = new dataSet(d); //this does not work because D is not defined
// it works as expected!
console.log(currentSet.item);
document.write("currentSet.item: " + currentSet.item);
document.write("\n<br>");
document.write("c: " + c);
document.write("\n<br>");
// also works as expected, it will show undefined
console.log(dSet.item);
document.write("dSet.item: " + dSet.item);
document.write("\n<br>");
document.write("d: " + d);
}
<button onclick="buildSet()">SET TEST</button>