因此,我创建了一个HTML文件,其中包含带有标签的按钮,例如:名字,姓氏等
我需要对按钮进行编程,以便当用户单击它时,拳头名称按钮应该消失,而在<div>
中,您会看到名称“ John Doe”
我已经在我的.js文件中创建了此文件:
// create a JavaScript object here with the following fields: firstName, lastName, jobTitle, homeOffice
var demo = {
firstName : "Waseem",
lastName : "Qazi",
jobTitle : "Traveler Care",
homeOffice : "Penn. field",
tellMeMore : "Exicted to re-start my coding adventure again. Been a while
since I had coded. Looking forward to all the learning and growth this
amazing oppportunity will present."
givefirstname : function() {
return this.firstName;
};
使用jQuery和上面的对象,在单击相应的按钮时显示信息。
如何在HTML文件中调用此函数,以便每个函数将相应的数据返回到屏幕上?
我在HTML文件中的呼叫行:
<li>
<a class="selected" href="">
<button type="button" onclick=demo.givefirstname>
First Name
</button>
</a>
</li>
<br>
答案 0 :(得分:0)
您需要调用该函数,并且需要添加代码以将按钮替换为返回的内容。
在下面的代码中,我将<a>
更改为<div>
,因为锚点中没有按钮,单击锚点将尝试访问该链接。
var demo = {
firstName: "Waseem",
lastName: "Qazi",
jobTitle: "Traveler Care",
homeOffice: "Penn. field",
tellMeMore: `Exicted to re-start my coding adventure again. Been a while
since I had coded.Looking forward to all the learning and growth this
amazing oppportunity will present.`,
givetitle: function() {
return this.jobTitle;
},
givefirstname: function() {
return this.firstName;
},
givelastname: function() {
return this.lastName;
}
};
function replaceMe(element, contents) {
element.parentElement.innerHTML = contents;
}
<ul>
<li>
<div class="selected">
<button type="button" onclick="replaceMe(this, demo.givefirstname())">
First Name
</button>
</div>
</li>
<li>
<div class="selected">
<button type="button" onclick="replaceMe(this, demo.givelastname())">
Last Name
</button>
</div>
</li>
<li>
<div class="selected">
<button type="button" onclick="replaceMe(this, demo.givetitle())">
Job Title
</button>
</div>
</li>
</ul>
答案 1 :(得分:0)
您可以替换或隐藏/显示一些dom元素。我要和后者一起去。我还将使giveFirstName
方法成为showValue
方法,以便更加灵活。
var demo = {
firstName : "Waseem",
lastName : "Qazi",
jobTitle : "Traveler Care",
homeOffice : "Penn. field",
tellMeMore : "Exicted to re-start my coding adventure again. Been a while since I had coded. Looking forward to all the learning and growth this amazing oppportunity will present.",
showValue : function(key, el) {
el.getElementsByTagName('span')[0].style.display = 'none';
var paragraph = el.getElementsByTagName('span')[1];
paragraph.style.display = 'inline';
paragraph.innerHTML = this[key];
},
}
p.value {
display: none;
}
<li>
<a class="selected" onclick="demo.showValue('firstName', this)">
<span class="title">First Name</span>
<span class="value"></span>
</a>
</li>