Home  >  Article  >  Web Front-end  >  The encapsulated function in jquery passes the current element

The encapsulated function in jquery passes the current element

小云云
小云云Original
2018-01-12 13:12:171776browse

This article mainly introduces you to the method of encapsulating functions in jquery to transfer the current element. The article gives detailed sample code, which has certain reference and learning value for everyone. Friends who need it can take a look below. Hope it helps everyone.

I recently encountered a problem at work. I need to perform ajax operations on a group of elements on the page. The structure is as follows:

<p id="aid"></p> 

<p id="aid"></p> 

<p id="aid"></p> 

<p id="aid"></p> 

<p id="stop">Stop here</p> 

<p id="aid"></p> 

<p id="aid"></p> 

<p id="aid"></p>

Writing the traversal function

function a() {

      $('p').each(function () {

        var that = $(this);

        var id = that.attr('id');

        b(id, that)

      })

    }

First execute function a () Traverse each element, and then execute the b() function for ajax

function b(aId,that) {

      $.ajax({

        url: 'ajaxHandler.ashx',

        data: { aid: aid },

        dataType: 'text',

        type: 'post',

        async: true,

        success: function (data) {

          var content = '';

          if (data == 'true') {

            content = "正确";

          } else {

            content = "错误";

          }

          that.html(content);

        }

      })

    }

Assign different values ​​to the clicked element based on the return value

Because some html elements have the same style, there is no way Assign value according to $("#id").html("Assignment");

Use this here to assign the return value to the currently clicked element

Because the page function is nested, So you need to pass the current element,

But due to various reasons, it may be difficult to use this in the end and still get the correct current element. Therefore, you can use a variable to store this:

var that = $(this); and then just use it

Related recommendations:

ajax encapsulation function jsonp usage

Introduction Several encapsulation functions in javascript-ecma

PHP encapsulation function to generate random string verification code

The above is the detailed content of The encapsulated function in jquery passes the current element. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn