单击按钮后,我正在尝试更改我的姓氏。
我目前正在使用jQuery.data来做到这一点。虽然我知道这些可以使用其他形式来完成,但我需要在这里为我的应用程序使用 jQuery.data。
这是我到目前为止的标记代码:
<div id="container">
My complete name is <span></span> D. <span></span>
</div>
<button type="button" id="btnID" onclick="changebtn()">Set Last Name to Smith </button>
这是我的jQuery代码:
var holder = $( "#container" )[0];
jQuery.data( holder, "data", {
firstname: "Sam",
lastname: "Norton"
});
$( "span:first" ).text( jQuery.data( holder, "data" ).firstname );
$( "span:last" ).text( jQuery.data( holder, "data" ).lastname );
function changebtn(){
}
这是我的jSFIDDLE:http://jsfiddle.net/vzzscnmr/1/
有什么想法吗?
注意:我们需要专门在这一部分使用 jQuery.data,而不是一个简单的 JQUERY 解决方案。
试试这个:
var holder = $( "#container" )[0];
jQuery.data( holder, "data", {
firstname: "Sam",
lastname: "Norton"
});
setNames();
$('#btnID').click(function(event){
event.preventDefault() ;
jQuery.data( holder, "data", {firstname: "Smith"});
setNames();
});
function setNames() {
$( "span:first" ).text( jQuery.data( holder, "data" ).firstname );
$( "span:last" ).text( jQuery.data( holder, "data" ).lastname );
}
- 还将 html
onclick
更改为 jQuery 处理程序...
JSFiddle here
我已经很好地注释了代码,而不是在这里用散文来解释它。你的问题并没有很好地解释你想要实现的目标,所以如果我的答案偏离了基础,那么请告诉我。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div id="nameContainer">My complete name is <span></span> D. <span></span></div>
<button id="theButton">Set Last Name to Smith</button>
<script>
$(function () {
// Instead of grabbing the first element using [0]
// you can just use the :first selector
var nameCont = $("#nameContainer:first");
// You can attach data directly to selections
// I am assuming you need the data to be attached
// to something because you want to use it
// later... otherwise there would not be much
// reason to save it like this.
nameCont.data({
firstname: "Sam",
lastname: "Norton"
});
// Simply find the span and then set the text
nameCont.find("span:first").text(nameCont.data("firstname"));
nameCont.find("span:last").text(nameCont.data("lastname"));
// Using the `onclick` HTML attribute is something
// people used to do "in the old days". Putting your
// events in your Javascript is a neater way of doing
// it. jQuery has a host of events you can use, such
// as this click event:
$("#theButton").click(function () {
var newLastname = "Smith";
// Set the new name
nameCont.find("span:last").text(newLastname);
// You are using the .data() method so I assume
// you want to reflect the change there as well:
nameCont.data("lastname", newLastname);
});
});
</script>
你不需要data
来执行此操作。将包含名称的字符串传递给 .text()
方法。
var holder = $( "#container" ),
firstnameElement = holder.find('span:first'),
lastnameElement = holder.find('span:last');
firstnameElement.text('Sam');
lastnameElement.text('Norton');
function changebtn(){
lastnameElement.text('Smith');
}
$('#btnID').click(changebtn);
其次,so可以通过在代码中绑定事件来清理html,而不是设置onclick
属性。
你更新的小提琴,看看它的实际效果。