简体   繁体   English

如何防止javascript中的重复条目?

[英]how to prevent duplicated entries in javascript?

i have a problem in preventing duplicates from being entered, i'm generated radio buttons dynamically in 2 pages at the same time using exactly one button, i take the label from the user and generate a radio button from that label, i want to prevent the user from entering 2 identical labels, here's the script which generates radios for the 2 pages any help will be appreciated 我有一个问题,防止输入重复,我只使用一个按钮同时动态生成两个页面的单选按钮,我从用户拿取标签,并从该标签生成一个单选按钮,我想防止用户输入2个相同的标签,这里是为2页生成无线电的脚本,任何帮助将不胜感激

function createRadioElement(elem, label, checked) {
var id = 'option1_' + label;
$('#after').append($('<input />', {
    'type': 'radio',
    'fieldset':'group',
    'name': 'option1',
    'id': id,
    'data-role': 'controlgroup',
    'data-theme':'b',
    'value': '1'}));
$('#after').append('<label for="' + id + '">'+ label + '</label>').trigger('create');}

function createRadioFortSecondPage(elem, label, checked) {
var id = 'option1_' + label;
$('#Inserthere').append($('<input />', {
    'type': 'radio',
    'fieldset':'group',
    'name': 'option1',
    'id': id,
    'data-role': 'controlgroup',
    'data-theme':'b',
    'value': '1'}));
$('#Inserthere').append('<label for="' + id + '">'+ label + '</label>').trigger('create');}

that's the function i wrote to prevent duplicates: 这是我写的函数,以防止重复:

function checkDublicates(){
     var isExist=true;
     var x = document.getElementById('option').value;
     var labels = [];   
$('#after input[type=radio]').each(function() {
     labels.push($('label[for='+$(this).attr('id')+']').text());


    });
    for(var i=0;i<labels.length;i++){

    if(x==labels[i])
    {
        isExist=false;}
        else{
        isExist=true;}
      }
    return isExist;}

and that's the button action: 那就是按钮动作:

$('#AddButton').click(function(){
     var exist=checkDublicates();
     <!--var isEmpty=validate();-->
    <!--if(exist==true){
        <!--alert("Duplicates Are Not Allowed!");
        <!--}else{
    var y=document.getElementById('question').value
    document.getElementById('headTitle').innerHTML=y;
    if(exist==false){
        alert("Duplicates Not Allowed!")
    }else{
    createRadioElement(this,$('#option').val(),true);
    createRadioFortSecondPage(this,$('#option').val(),true);
  }

  });

Just use $.inArray(val, arr) it will work ! 只需使用$.inArray(val, arr)就行了! http://api.jquery.com/jQuery.inArray/ http://api.jquery.com/jQuery.inArray/

But just a comment concerning your code. 但只是关于你的代码的评论。

Replace 更换

document.getElementById('question').value

by 通过

$('#question').val()

and

document.getElementById('headTitle').innerHTML=y

by 通过

$('#headTitle').html(y)

Will be much cleaner ;-) 会更清洁;-)

You can use this handy function to push elements into an array and check for duplicates at the same time. 您可以使用这个方便的功能将元素推入数组并同时检查重复项。 It'll return true if it catches a duplicate. 如果它捕获重复,它将返回true

var noDupPush = function (value, arr) {

    var isDup = false;

    if (!~$.inArray(value, arr)) {
        arr.push(value);
    } else {
        isDup = true;
    }

    return isDup;

};

// You can use it like this

var arr = ['green'];
if (noDupPush('green', arr)){
  // Dup exists
}
// Or else it will just push new value to array

You could generate an id that includes the text of the label and then very quickly check for the existence of an element containing that text. 您可以生成包含标签文本的id,然后快速检查是否存在包含该文本的元素。 For example: 例如:

function generateLabelId( userinput ){ 
    return 'awesomelabel_' + userinput.replace(/\W/g,'');
}

var label = document.getElementById(generateLabelId( userinput ));
var labelDoesNotExist = (label == undefined );

if (labelDoesNotExist){
    // create your element here
    // making sure that you add the id from generateLabelId
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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