【问题标题】:Separating male and female names with javascript/html?用javascript/html分隔男性和女性名字?
【发布时间】:2019-08-02 09:45:17
【问题描述】:

我有一个涉及 css 和 javascript 的随机名称生成器代码。按照现在的代码,我可以输入任何名字(不分性别),点击生成按钮,然后会弹出一个随机的名字和姓氏。唯一的问题是,我希望能够为男性、女性和中性名称创建单独的按钮。

我尝试为姓名和女性姓名创建单独的 div id,复制 javascript 并将代码部分更改为“femalename”和“malename”,但这破坏了格式并使其如此,当我按下其中一个生成按钮,两个 div 都会生成一个名称。

<!DOCTYPE HTML>
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
<title>Random name generator</title>
<meta charset='utf-8' />

<style type='text/css'>

    #name {
	    color : #444;
		font : bold 51px times, Times New Roman, times-roman, georgia, serif;
		letter-spacing : -2px;
		line-height : 44px;
		text-align : center;
		text-transform: uppercase;
	}
	
	#refresh {
		font : normal 11px Gill Sans, Verdana;
		letter-spacing : 2px;
		line-height : 14px;
		text-align : center;
		text-transform : uppercase;
	}
	
	a {
	    color : #666;
	}
	
	a:hover {
	    color : #999;
	}
	
</style>
</head>

<body>
		<script type='text/javascript'>
			first = ['abbie ', 'abby ', 'abu ', 'alec ', 'alek ', 'aleksander ', 'alex ', 'alexander ', 'aaron ', 'adam ', 'andrew ', 'anthony ', 'archer ', 'arthur ', 'austin '];
			last = ['williamson', 'davidson', 'edwards', 'ingram', 'olsen'];

			name = "";
			length = Math.floor(Math.random()) + 1; 
			for (i = 0; i < length; i++)
				name += (first[Math.floor(Math.random()*first.length)]
						 + last[Math.floor(Math.random()*last.length)]);
			name = name.charAt(0) + name.slice(1);
			document.write("<p id='name'>" + name + "</p>"); 
		</script>
		<p id="refresh">
			<a href='#' onclick='window.location.reload()'>generate a new one</a>
		</p>
	</body>
</html>

【问题讨论】:

  • 你需要两个数组;一个用于女性名字,一个用于男性名字。最好的办法是手动制作这些,因为您需要一个极其复杂的深度学习算法来计算出什么是男性名字和什么是女性名字。
  • 你怎么知道一个名字是男是女?
  • 谁来选择名字是男是女?用户点击generate a new one时是否选择了这个?
  • @yalda 我想创建两个单独的按钮(一个写着“生成女性名字”,一个写着“生成男性名字”),而不是只有一个写着“生成新名字”的按钮。 "

标签: javascript html css


【解决方案1】:

你觉得这个怎么样?

const
  // Identifies HTML elements
  buttons = document.getElementsByClassName("btns"),
  display = document.getElementById("display"),

  // Identifies arrays of names
  girls = ['abbie', 'abby'],
  boys = ['abu', 'alec', 'arthur'],
  whatevs = ['alex', 'archer',  'austin'],
  lastNames = ['williamson', 'davidson', 'edwards', 'ingram', 'olsen'];

// Runs the makeName function when a button is clicked
document.addEventListener("click", makeName);

// Defines the makeName function (`event` is the triggering click event)
function makeName(event){
  
  // Remembers what was clicked
  const clickedThing = event.target;
  
  // Declares a variable to hold the appropriate array
  let chosenList;
  
  // Makes sure the click was on a button before proceeding
  if(clickedThing.classList.contains("btns")){
  
    // Sets the appropriate list depending on which button was clicked
    if(clickedThing.value == "girl"){ chosenList = girls; }
    else if(clickedThing.value == "boy"){ chosenList = boys; }
    else { chosenList = whatevs; }

    // Identifies names (retrieved using the `randFrom` function)
    const
      first = randFrom(chosenList), // Chooses a name from the specified list
      last = randFrom(lastNames), // Chooses a lastName
      fullName = `${first} ${last}`; // Puts them together

    // Shows the result on the page
    display.innerHTML = fullName;
  }
}

// Gets a random element from an array
function randFrom(array){
  const index = Math.floor(Math.random() * array.length);
  return array[index];
}
#display {
  color: #444;
  font: bold 51px times, Times New Roman, times-roman, georgia, serif;
  letter-spacing: -2px;
  line-height: 44px;
  text-align: center;
  text-transform: uppercase;
}
<button class="btns" value="girl">girl</button>
<button class="btns" value="boy">boy</button>
<button class="btns" value="whatevs">whatevs</button>

<p id="display"></p>

【讨论】:

    【解决方案2】:

    我会更改函数以在 HTML 中接受性别,并在加载时运行该函数。

    这里还有一个带有“任何性别”选项的示例:https://codepen.io/kboedges/pen/qeXmqK?editors=1111

    const maleFirst = ["abu", "alec", "alek"];
    const femaleFirst = ["abbie", "abby", "katie", "leah"];
    const last = ["williamson", "davidson", "edwards", "ingram", "olsen"];
    
    // Function
    function generateName(gender) {
      const randomLast = last[Math.floor(Math.random() * last.length)];
      const randomMaleName = `${maleFirst[Math.floor(Math.random() * maleFirst.length)]} ${randomLast}`;
      const randomFemaleName = `${femaleFirst[Math.floor(Math.random() * femaleFirst.length)]} ${randomLast}`;
      
      // Insert into HTML
      const p = document.getElementById('name');
      p.innerHTML = gender === 'female' ? randomFemaleName : randomMaleName;
    }
    
    // On first run
    generateName('male');
    #name {
      color: #444;
      font: bold 51px times, Times New Roman, times-roman, georgia, serif;
      letter-spacing: -2px;
      line-height: 44px;
      text-align: center;
      text-transform: uppercase;
    }
    
    #refresh {
      font: normal 11px Gill Sans, Verdana;
      letter-spacing: 2px;
      line-height: 14px;
      text-align: center;
      text-transform: uppercase;
    }
    
    a {
      color: #666;
    }
    
    a:hover {
      color: #999;
    }
    <p id='name'></p>
    <p id="refresh">Generate a...
      <a href='#' onclick="generateName('female')">female name</a>
      <a href='#' onclick="generateName('male')">male name</a>
    </p>

    【讨论】:

      【解决方案3】:

      如果我没有错过了解,您需要两个操作来在不同的容器中创建和显示名称。

      <!DOCTYPE HTML>
      <html xmlns='http://www.w3.org/1999/xhtml'>
      <head>
          <title>Random name generator</title>
          <meta charset='utf-8' />
      
          <style type='text/css'>
      
              .name {
          	    color : #444;
          		font : bold 51px times, Times New Roman, times-roman, georgia, serif;
          		letter-spacing : -2px;
          		line-height : 44px;
          		text-align : center;
          		text-transform: uppercase;
          	}
          	
          	.refresh {
          		font : normal 11px Gill Sans, Verdana;
          		letter-spacing : 2px;
          		line-height : 14px;
          		text-align : center;
          		text-transform : uppercase;
          	}
          	
          	a {
          	    color : #666;
          	}
          	
          	a:hover {
          	    color : #999;
          	}
          	
          </style>
      </head>
      
      <body>
      	<p id="firstName" class="name"></p>
          <p class="refresh">
      		<a href='#' onclick='generateName("firstName")'>generate a first name</a>
      	</p>
          <p id="secondName" class="name"></p>
          <p class="refresh">
              <a href='#' onclick='generateName("secondName")'>generate a second name</a>
          </p>
          <script type='text/javascript'>
              function generateName(containerId) {
                  first = ['abbie ', 'abby ', 'abu ', 'alec ', 'alek ', 'aleksander ', 'alex ', 'alexander ', 'aaron ', 'adam ', 'andrew ', 'anthony ', 'archer ', 'arthur ', 'austin '];
                  last = ['williamson', 'davidson', 'edwards', 'ingram', 'olsen'];
      
                  name = "";
                  length = Math.floor(Math.random()) + 1; 
                  for (i = 0; i < length; i++)
                      name += (first[Math.floor(Math.random()*first.length)] + last[Math.floor(Math.random()*last.length)]);
                  name = name.charAt(0) + name.slice(1);
                  document.getElementById(containerId).innerHTML = name;
                  
              }        
          </script>
      
      </body>
      </html>

      【讨论】:

        【解决方案4】:

        这是一个带有单个数组的 firstNames 的答案。名字的结构已更改为对象数组。

        我确实使用了很多 ES6 'fat-arrow' 函数,并试图使这些函数尽可能地可重用。这实际上是一种乐趣! ;)

        const resultsPane = document.querySelector('.random-name-results ul'),
          generateBtn = document.querySelector('.refresh-random-name');
        
        const filterByGender = gender => name => gender.includes(name.gender);
        
        const getRandom = arr => arr[Math.floor(Math.random() * arr.length)];
        
        const findName = (gender) => {
          const firstNames = [
            {
              name: 'abigail',
              gender: 'female',
              variations: ['abigail', 'abbie', 'abby']
            },
            {
              name: 'abu',
              gender: 'neutral',
              variations: ['abu']
            }, {
              name: "alec",
              gender: "neutral",
              variations: ['alec', 'alex', 'alexander', 'alek', 'aleksander']
            }, {
              name: 'aaron',
              gender: 'male',
              variations: ['aaron', 'aron', 'aram', 'aroon', 'arrun', 'arun', 'aharon']
            }, {
              name: 'adam',
              gender: 'male',
              variations: ['adam', 'addam', 'adham', 'atem']
            }, {
              name: 'andrew',
              gender: 'male',
              variations: ['andrew', 'andy', 'andre', 'andrej']
            }, {
              name: 'addison',
              gender: 'neutral',
              variations: ['addison', 'addy', 'addie']
            }, {
              name: 'cameron',
              gender: 'neutral',
              variations: ['cameron', 'cam', 'cammie']
            }, {
              name: 'kathryn',
              gender: 'female',
              variations: ['kathryn', 'katherine', 'kathy', 'catherine', 'cathy', 'kate', 'katy', 'cate', 'katya']
            }
          ];
          const last = ['williamson', 'davidson', 'edwards', 'ingram', 'olsen'];
        
          const findGender = filterByGender(gender),
            filteredList = firstNames.filter(findGender),
            firstName = getRandom(getRandom(filteredList).variations),
            lastName = getRandom(last);
          return `${firstName} ${lastName}`
        }
        
        generateBtn.addEventListener("click", function(){
          const gender = document.querySelector("input[name='gender']:checked").value;
          let name = findName(gender),
              nameEl = document.createElement('li');
          nameEl.innerText = name;
          resultsPane.innerText = "";
          resultsPane.appendChild(nameEl);
        })
        .random-name-container {
          width: 96vw;
          height: 95vh;
          border: 2px solid palevioletred;
          border-radius: 2vmin;
          padding: .5vmin;
          display: grid;
          grid-template-areas: 'head head'
                               'actions results'
                               'actions foot';
          grid-template-rows: 8vh 1fr 30px;
          grid-template-columns: 30vw 1fr;
          overflow: scroll;
          }
        
        .random-name-container header {
          grid-area: head;
          background-color: bisque;
        }
        
        header h1 {
          margin: auto auto 0 auto;
        }
        header p {
          margin: 0;
        }
        
        .random-name-container footer {
          grid-area: foot;
          background-color: bisque;
        }
        
        .random-name-results {
          grid-area: results;
          background-color: gainsboro;
          width: 100%;
          height: 100%;
        
        }
          .random-name-actions {
            display: flex;
            grid-area: actions;
            flex-direction: row;
            flex-wrap: wrap;
          }
        
          .random-name-actions > * {
            width: 95%;
          }
        
          .random-name-actions fieldset > * {
            display: block;
          }
          <article class='random-name-container'>
            <header>
              <h1>Random Name Generator</h1>
              <p>Choose your preferred gender, and give it a spin!</p>
            </header>
            <section class='random-name-results'>
              <ul></ul>
            </section>
            <section class='random-name-actions'>
              <fieldset>
                <label><input type='radio' name='gender' value='female neutral' checked />Female</label>
                <label><input type='radio' name='gender' value='male neutral' />Male</label>
                <label><input type='radio' name='gender' value='neutral' />Gender-neutral</label>
              </fieldset>
        
        			<input type='button' class='refresh-random-name btn' value='Generate another!'>
            </section>
            <footer>The name game</footer>
          </article>

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-09-02
          • 2021-01-13
          • 2013-09-01
          • 2013-06-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多