var change= document.getElementById("change");
var color= document.getElementById("color");
var result=document.getElementById("result");
function changecolor(){
change.addEventListener("click",randomColor());
}
function randomColor(){
for(var i=0; i<1000; i++){
var randomColor ='#'+Math.random().toString(16).substr(2,6);
color.style.background=randomColor;
result.innerHTML="current color is"+randomColor;
}
}
https://jsfiddle.net/z9yu3tjm/
我有这样的功能来生成随机颜色。每次点击都会产生随机颜色。如果函数运行5次,我想显示警报。并且该功能将停止(无法点击)。该怎么做
答案 0 :(得分:1)
维护一个全局变量,例如 import android.net.Uri;
import android.support.design.widget.TabLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
List<String> matchNumberArray = new ArrayList<String>();
//String matchNumberArray[] = {};
ArrayAdapter matchNumberAdapter = new ArrayAdapter<String> (this, R.layout.previous_fragment, matchNumberArray);
List<String> teamNumberArray = new ArrayList<String>();
// String teamNumberArray[] = {};
ArrayAdapter teamNumberAdapter = new ArrayAdapter<String>(this, R.layout.previous_fragment, teamNumberArray);
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml. @Override
// Handle item selection
switch (item.getItemId()) {
case R.id.saveMenuItem:
return true;
case R.id.ScreenShotMenuItem:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void openScreenshotToast(MenuItem item) {
Toast toast = Toast.makeText(getApplicationContext(), "Screenshot button pressed", Toast.LENGTH_SHORT);
toast.show();
}
public void saveMatchData (MenuItem item) {
//save button in my menu
//creates a toast to notify that it has been pressed
Toast toast = Toast.makeText(getApplicationContext(), "Save button pressed", Toast.LENGTH_SHORT);
toast.show();
// create an EditText for matchNumberInput
EditText matchNumberET = (EditText) findViewById(R.id.matchNumberInput);
//assign value of matchNumberET(Edit Text) to match number
EditText matchNumber = (EditText) matchNumberET.getText();
//attempted to assign to an int
int matchNumberValue = Integer.parseInt(matchNumber);
//same as abover just tried a different way that i read online
EditText teamNumberDT = (EditText) findViewById(R.id.teamNumberInput);
int teamNumber = Integer.parseInt(teamNumberDT.getText().toString());
int i;
//i have an array for matchNumber values and teamNumber values
//they start empty and as of now still are
//
for (i = 0, i <= matchNumberArray.size(), i++);{
if (matchNumberValue == matchNumberArray.get(i)){
//code to add matchNumber if not already there
}
//both of these different ways to do this give me errors
}
if (teamNumberArray.get(i) == teamNumber) {
//code to add teamNumber if not already there
}
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Main Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
@Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
@Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (getArguments().getInt(ARG_SECTION_NUMBER) == 1) {
View rootView = inflater.inflate(R.layout.fieldmap_fragment, container, false);
return rootView;
} else if (getArguments().getInt(ARG_SECTION_NUMBER) == 2) {
View rootView = inflater.inflate(R.layout.datainput_fragment, container, false);
return rootView;
} else {
View rootView = inflater.inflate(R.layout.previous_fragment, container, false);
return rootView;
}
}
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
@Override
public int getCount() {
// Show 3 total pages.
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "FieldMap";
case 1:
return "Match Data";
case 2:
return "Previous";
}
return null;
}
}
count
答案 1 :(得分:0)
只有你必须使用is counter变量。 https://jsfiddle.net/z9yu3tjm/1/ 我已经更新了你的代码,这里是JS代码。
var change= document.getElementById("change");
var color= document.getElementById("color");
var result=document.getElementById("result");
function changecolor(){
change.addEventListener("click",randomColor());
}
var i=0;
function randomColor(){
if(i<5){
i++;
var randomColor ='#'+Math.random().toString(16).substr(2,6);
color.style.background=randomColor;
result.innerHTML="current color is"+randomColor;
}else{
alert('5 times run...');
}
}
答案 2 :(得分:0)
保留一个计数器以保持点击次数,一旦超过限制,删除点击属性,以便不再触发事件。
使用change.removeAttribute('onclick');
删除点击事件。
示例代码段:
var change = document.getElementById("change");
var color = document.getElementById("color");
var result = document.getElementById("result");
var max_number_times = 5;
var number_of_times = 0;
function changecolor() {
change.addEventListener("click", randomColor());
}
function randomColor() {
if (number_of_times < max_number_times) {
number_of_times++;
for (var i = 0; i < 1000; i++) {
var randomColor = '#' + Math.random().toString(16).substr(2, 6);
color.style.background = randomColor;
result.innerHTML = "current color is" + randomColor;
}
} else {
alert("5 times done")
change.removeAttribute('onclick');
}
}
<button id="change" onclick="changecolor()">change color</button>
<section id="color">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Harum, ullam ex totam dolorem cupiditate! Velit autem, obcaecati magni molestiae architecto.</p>
<p id="result"></p>
</section>
答案 3 :(得分:0)
对于架构的关注,我们建议不要修改randomColor
函数,以添加另一个监视randomColor
调用的函数。
function changecolor(){
change.addEventListener("click",monitor);
}
randomColor.calls = 0;
function monitor () {
randomColor.calls ++;
randomColor.calls <=5 && randomColor(...arguments);
}
只为代码优雅:)