简体   繁体   中英

Changing the contents of an input/div/span etc

I add a .listen class to various elements on my page, could be a button, could be an input, div, span etc.

$('.listen').on('click', this._init.bind(this));

In the method I wish to replace text in the element that was clicked.

p._init = function(e){
    $(e.currentTarget).val('new data');
};

The above works for input elements, but not for things like divs. Is there a way to change the data on any type of elements or will I have to use a switch to test for the variations?

You could get a little fancy and check if the element has a value property, and change methods based one that, something like

p._init = function(e){
    $(e.currentTarget)['value' in e.currentTarget ? 'val' : 'text']('new data');
};

FIDDLE

Unless you're adding value properties to elements that don't natively have value properties, that should work.

For input it's val() for divs and stuff it's text().

If you wanna do everything with a single event, you can do something like:

$('.listen').on(...
{
    if($(this).is('input')) 
    { 
        use val() 
    }
    else
    {
       use text()
    }
}

Try this DEMO

    $(document).ready(function(){

     _init = function(e){ 
       if(e.target.nodeName=='SPAN'||e.target.nodeName=='DIV')
           $(this).text('new data');
       else if(e.target.nodeName=='INPUT')
          $(this).val('new data');
      };
   $('.listen').on('click', _init);

 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM