Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/84.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 更新输入字段时更改HTML5数据属性_Javascript_Html - Fatal编程技术网

Javascript 更新输入字段时更改HTML5数据属性

Javascript 更新输入字段时更改HTML5数据属性,javascript,html,Javascript,Html,我试图使用一些javascript在向输入字段输入文本时更新与div关联的数据属性(datafoo)。有什么想法吗?我完全被难住了 <div data-foo=""></div> <textarea name="extraoptions">bar</textarea> 酒吧 如果您可以按id或按类获取此div,可以这样说 <div id="div1" data-foo=""></div> 使用jQuery,您可以执行以

我试图使用一些javascript在向输入字段输入文本时更新与div关联的数据属性(datafoo)。有什么想法吗?我完全被难住了

<div data-foo=""></div>
<textarea name="extraoptions">bar</textarea>

酒吧

如果您可以按id或按类获取此div,可以这样说

<div id="div1" data-foo=""></div>

使用jQuery,您可以执行以下操作:

jQuery("body").find("div[data-foo]").html('My New HTML Content For DIV with data-foo attribute');
那么,为什么要使用:

jQuery("body")
反对:

$("body")

你可以问吗?这确保我们不会和任何可能在网站上使用的其他库发生任何冲突,认为它是编写jQuery的一种安全方式。

< P>我只是用我的小提琴为你编写代码。用这个。它会正常工作。我希望这就是你现在想要的

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>
DOM
准备就绪时使用它


如果你需要我的帮助。请通过搜索
yeshansachithak

找到我的任何社交网络,可能是jQuery吗?-可能重复的是,我应该提到我试图使用jquery来实现这一点,但我一直在解决这个看似基本的过程。如何引用div取决于您自己,但大致如下:
div.setAttribute('data-foo',textarea.value)
<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>
//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);
});