Change text of all elements with specific data-attribute

北战南征 提交于 2019-12-11 11:53:57

问题


I'm currently trying to use jQuery to change the text of a number of elements to the value of a specific data-attribute.

For example:

index.html
----------
<h1 data-change="text2">text1</h1>
<p data-change="paragraph2">paragraph1</p>

I want to change 'text1' to 'text2' and 'paragraph1' to 'paragraph2' (the value of data-change for that specific element).

How would I go about doing this?

I assumed I would be able to 'select' all of the elements with the data-attribute 'data-change' and then just do a simple $(this).text($(this).data('change')); or something.


回答1:


You can do this:

$('[data-change]').each(function(){
    $(this).text($(this).data('change'));
});

You can iterate over the elements and change its text.




回答2:


.text method could accept a callback function.

$('[data-change]').text(function() {
  return $(this).data('change');
});



回答3:


How would you like this~

-html-


   <select id="" name="" class="input_select">

          <option value="text2" selected="selected">text2</option>
           <option value="paragraph2">paragraph2</option>
   </select>

  <h1 class="text2">text1</h1>
   <p class="paragraph2">paragraph1</p>
 </pre>

-js- $(document).ready(function(){

$('.input_select').change(function(){ var valitem = $(this).val() if (valitem == 'text2') { $('.text2').text(valitem) }else{ $('.paragraph2').text(valitem) } }) });


来源:https://stackoverflow.com/questions/23258618/change-text-of-all-elements-with-specific-data-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!