Catch paste input

后端 未结 17 2102
名媛妹妹
名媛妹妹 2020-11-22 08:09

I\'m looking for a way to sanitize input that I paste into the browser, is this possible to do with jQuery?

I\'ve managed to come up with this so far:



        
17条回答
  •  孤城傲影
    2020-11-22 08:23

    This method uses jqueries contents().unwrap().

    1. First, detect the paste event
    2. Add a unique class to the tags that are already in the element into which we are pasting.
    3. After a given timeout scan through all the contents unwrapping tags that don't have the class that you set earlier. Note: This method does not remove self closing tags like
      See an example below.

      //find all children .find('*') and add the class .within .addClass("within") to all tags
      $('#answer_text').find('*').each(function () {
      $(this).addClass("within");
      });
      setTimeout(function() {
      $('#answer_text').find('*').each(function () {
          //if the current child does not have the specified class unwrap its contents
          $(this).not(".within").contents().unwrap();
      });
      }, 0);
      

提交回复
热议问题