当将文本输入输入字段时,我试图使用一些javascript来更新与div关联的数据属性(data-foo)。有什么想法吗?我完全不知所措。
<div data-foo=""></div>
<textarea name="extraoptions">bar</textarea>发布于 2014-04-23 05:41:19
我只是在我的小提琴里给你编密码。使用这个JSFIDDLE。它会正常工作的。我希望这是你现在想要的。
HTML5
<input id="text" type="text"/>
<br/><br/>
<div id="result" data-foo="">This is the div with `data-foo` attribute. While you typing this div `data-foo` attribute will change as input valu. If you want to check it. Just click on below button.</div>
<br/>
<button id="test">What is my DIV `data-foo` now?</button>jQuery
//FOR TESTING - This function will help you to test the below function is working or not
$("#test").click(function(){
var value = $('#result').attr('data-foo');
alert(value);
});
//This function will auto change `data-foo` while you typing
$("#text").keyup(function(){
var text = $(this).val();
$("#result").attr('data-foo',text);
});当DOM准备好时使用它。
如果你需要我的帮助。请通过搜索yeshansachithak找到我的任何一个社交网络。
发布于 2014-04-23 04:59:45
使用jQuery,您可以这样做:
jQuery("body").find("div[data-foo]").html('My New HTML Content For DIV with data-foo attribute');那么,为什么要使用:
jQuery("body")反对:
$("body")你可以问吗?这确保了我们不会与站点上可能使用的任何其他库发生冲突,认为它是编写jQuery的一种安全方法。
发布于 2014-04-23 04:53:45
如果您可以通过id或类获得这个div,那么让我们说
<div id="div1" data-foo=""></div>然后你就能做到-
$("#div1").attr("data-foo", val)https://stackoverflow.com/questions/23234953
复制相似问题