如何防止重复追加数据到jquery / javascript中的表?

时间:2016-09-12 03:34:59

标签: javascript php jquery html

如何避免在表格中使用相同的数据?

以下是代码:

var a = 0;
    $(document).on("change", "#txtInput",function(){
      var inputLength = this.value.length;
      if (inputLength <= 9) { return; }

      $("#contenido").append("<tr><td>" + this.value + "</td></tr>");
      $("p").html('Total Bianuales: ' + (++a));
    });

2 个答案:

答案 0 :(得分:1)

存储您已添加的值,如果已添加输入值,请不要重新添加。

public class OverviewFragment extends Fragment implements GoogleApiClient.OnConnectionFailedListener{
    private static final String TAG = "OverviewFragment";
    private static final int GOOGLE_RC_SIGN_IN = 9001;
    private static final int TWITTER_RC_SIGN_IN = 140;

    private GoogleApiClient mGoogleApiClient;
    @BindView(R.id.sign_in_button) SignInButton mGoogleSigninButton;
    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_overview, container, false);
        ButterKnife.bind(this, rootView);

        mAuth = FirebaseAuth.getInstance();

        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user != null) {
                    // User is signed in
                    Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
                    finishOnboarding();
                } else {
                    // User is signed out
                    Log.d(TAG, "onAuthStateChanged:signed_out");
                }
                //updateUI(user);
            }
        };
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();
        mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
                .enableAutoManage(getActivity(),this)
                .addApi(Auth.GOOGLE_SIGN_IN_API,gso)
                .build();
        mGoogleSigninButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent signinIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
                startActivityForResult(signinIntent, GOOGLE_RC_SIGN_IN);
            }
        });

        return rootView;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //callbackManager.onActivityResult(requestCode,resultCode,data);

        if (requestCode == GOOGLE_RC_SIGN_IN){
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            if (result.isSuccess()) {
                GoogleSignInAccount account = result.getSignInAccount();
                handleGoogleAuthentication(account);
            } else {
                //Google Login Failed
                Log.d(TAG, "Google Login Failed "+result.getSignInAccount()+"Status is "+result.getStatus());
            }
        } else if (requestCode == TWITTER_RC_SIGN_IN) {
            //mTwitterLoginButton.onActivityResult(requestCode,resultCode,data);
        } else {
            //callbackManager.onActivityResult(requestCode,resultCode,data);
        }
    }


    private void handleGoogleAuthentication(GoogleSignInAccount account) {
        AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
        mAuth.signInWithCredential(credential).addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful()) {
                    //Save Credentials in Google Smart Lock
                    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
                    //updateUser(user);
                } else {
                    //
                    Log.d(TAG, "Login failed");
                }
            }
        });
    }
    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }
    private void finishOnboarding() {
        startActivity(new Intent(getActivity(), MainActivity.class));
    }
}

答案 1 :(得分:0)

基本上,您需要浏览表格两次,并检查每一行。这是一个带有示例的片段:

//Populate table
for(var i = 0; i<10; i++){
 $('table tbody').append('<tr><td>Row '+i+'</td></tr>');
 $('table tbody').append('<tr><td>Row '+i+'</td></tr>');
 }

//Go along the table twice and check. Remove if the same content.
function cleanTable(){
  for(var i = 0; i<$('table tbody tr').length; i++){
      for(var j = 0; j<$('table tbody tr').length; j++){
      if($('table tbody tr').eq(i).html() == $('table tbody tr').eq(j).html() && i != j){
        $('table tbody tr').eq(j).remove();
      }
    }
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onClick="cleanTable()">Clean</button>

<table>
  <tbody>
  </tbody>
</table>

<button onClick="cleanTable()">Clean</button>