jquery获取单选框复选框下拉框值jquery获取单选框（radio）复选框（checkbox）下拉框（select）的值，亲测可用。有什么疑问可以留言效果图：html代码： jquery 获取 ul li 的值: 全部 值一 值二 值三 值四 值五 jquery 获取 radio 的值: 全部 男 女 保密 jquery 获取 checkbox 的值: 全部 内容一 内容二 内容三 jquery 获取 select 的值: 全部 -请选择- 选择一 选择二 选择三 jquery代码：
jQuery input输入框回车生成标签，可删除，并获取标签的值
效果图如下：html代码 flat-ui标签 提取input中的标签 获取输入的值 CSS代码：*{margin: 0;padding: 0;list-style-type: none;text-decoration: none;} .box{width: 500px;margin: auto;} .bootstrap-tagsinput { background-color: white; border: 2px solid #ebedef; border-radius: 6px; margin-bottom: 18px; padding: 6px 1px 1px 6px; text-align: left; font-size: 0; } .bootstrap-tagsinput .badge { border-radius: 4px; background-color: #ebedef; color: #7b8996; font-size: 13px; cursor: pointer; display: inline-block; position: relative; vertical-align: middle; overflow: hidden; margin: 0 5px 5px 0; padding: 6px 28px 6px 14px; transition: .25s linear; } .bootstrap-tagsinput .badge > span { color: white; padding: 0 10px 0 0; cursor: pointer; font-size: 12px; position: absolute; right: 0; text-align: right; text-decoration: none; top: 0; width: 100%; bottom: 0; z-index: 2; } .bootstrap-tagsinput .badge > span:after { content: "x"; font-family: "Flat-UI-Pro-Icons"; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; line-height: 27px; } @media (hover: hover) { .bootstrap-tagsinput .badge { padding: 6px 21px; } .bootstrap-tagsinput .badge > span { opacity: 0; filter: "alpha(opacity=0)"; transition: opacity .25s linear; } .bootstrap-tagsinput .badge:hover { background-color: #16a085; color: white; padding-right: 28px; padding-left: 14px; } .bootstrap-tagsinput .badge:hover > span { padding: 0 10px 0 0; opacity: 1; -webkit-filter: none; filter: none; } } .bootstrap-tagsinput input[type="text"] { font-size: 14px; border: none; box-shadow: none; outline: none; background-color: transparent; padding: 0; margin: 0; width: auto !important; max-width: inherit; min-width: 80px; vertical-align: top; height: 29px; color: #34495e; } .tagsinput-primary { margin-bottom: 18px; } .tagsinput-primary .bootstrap-tagsinput { border-color: #1abc9c; margin-bottom: 0; } .tagsinput-primary .badge { background-color: #1abc9c; color: white; } .btn{background: #1ABC9C;border: none;color: #fff;padding: 10px;border-radius: 5px;margin-top: 10px;}jQuery代码：/* bootstrap-tagsinput v0.8.0 */ (function ($) { "use strict"; var defaultOptions = { tagClass: function(item) { return 'badge badge-info'; }, focusClass: 'focus', itemValue: function(item) { return item ? item.toString() : item; }, itemText: function(item) { return this.itemValue(item); }, itemTitle: function(item) { return null; }, freeInput: true, addOnBlur: true, maxTags: undefined, maxChars: undefined, confirmKeys: [13, 44], delimiter: ',', delimiterRegex: null, cancelConfirmKeysOnEmpty: false, onTagExists: function(item, $tag) { $tag.hide().fadeIn(); }, trimValue: false, allowDuplicates: false, triggerChange: true }; /** * Constructor function */ function TagsInput(element, options) { this.isInit = true; this.itemsArray = []; this.$element = $(element); this.$element.hide(); this.isSelect = (element.tagName === 'SELECT'); this.multiple = (this.isSelect && element.hasAttribute('multiple')); this.objectItems = options && options.itemValue; this.placeholderText = element.hasAttribute('placeholder') ? this.$element.attr('placeholder') : ''; this.inputSize = Math.max(1, this.placeholderText.length); this.$container = $(' '); this.$input = $(' ').appendTo(this.$container); this.$element.before(this.$container); this.build(options); this.isInit = false; } TagsInput.prototype = { constructor: TagsInput, /** * Adds the given item as a new tag. Pass true to dontPushVal to prevent * updating the elements val() */ add: function(item, dontPushVal, options) { var self = this; if (self.options.maxTags && self.itemsArray.length >= self.options.maxTags) return; // Ignore falsey values, except false if (item !== false && !item) return; // Trim value if (typeof item === "string" && self.options.trimValue) { item = $.trim(item); } // Throw an error when trying to add an object while the itemValue option was not set if (typeof item === "object" && !self.objectItems) throw("Can't add objects when itemValue option is not set"); // Ignore strings only containg whitespace if (item.toString().match(/^\s*$/)) return; // If SELECT but not multiple, remove current tag if (self.isSelect && !self.multiple && self.itemsArray.length > 0) self.remove(self.itemsArray[0]); if (typeof item === "string" && this.$element[0].tagName === 'INPUT') { var delimiter = (self.options.delimiterRegex) ? self.options.delimiterRegex : self.options.delimiter; var items = item.split(delimiter); if (items.length > 1) { for (var i = 0; i < items.length; i++) { this.add(items[i], true); } if (!dontPushVal) self.pushVal(self.options.triggerChange); return; } } var itemValue = self.options.itemValue(item), itemText = self.options.itemText(item), tagClass = self.options.tagClass(item), itemTitle = self.options.itemTitle(item); // Ignore items allready added var existing = $.grep(self.itemsArray, function(item) { return self.options.itemValue(item) === itemValue; } )[0]; if (existing && !self.options.allowDuplicates) { // Invoke onTagExists if (self.options.onTagExists) { var $existingTag = $(".badge", self.$container).filter(function() { return $(this).data("item") === existing; }); self.options.onTagExists(item, $existingTag); } return; } // if length greater than limit if (self.items().toString().length + item.length + 1 > self.options.maxInputLength) return; // raise beforeItemAdd arg var beforeItemAddEvent = $.Event('beforeItemAdd', { item: item, cancel: false, options: options}); self.$element.trigger(beforeItemAddEvent); if (beforeItemAddEvent.cancel) return; // register item in internal array and map self.itemsArray.push(item); // add a tag element var $tag = $('' + htmlEncode(itemText) + ''); $tag.data('item', item); self.findInputWrapper().before($tag); $tag.after(' '); // Check to see if the tag exists in its raw or uri-encoded form var optionExists = ( $('option[value="' + encodeURIComponent(itemValue) + '"]', self.$element).length || $('option[value="' + htmlEncode(itemValue) + '"]', self.$element).length ); // add if item represents a value not present in one of the 's options if (self.isSelect && !optionExists) { var $option = $(' ' + htmlEncode(itemText) + ' '); $option.data('item', item); $option.attr('value', itemValue); self.$element.append($option); } if (!dontPushVal) self.pushVal(self.options.triggerChange); // Add class when reached maxTags if (self.options.maxTags === self.itemsArray.length || self.items().toString().length === self.options.maxInputLength) self.$container.addClass('bootstrap-tagsinput-max'); // If using typeahead, once the tag has been added, clear the typeahead value so it does not stick around in the input. if ($('.typeahead, .twitter-typeahead', self.$container).length) { self.$input.typeahead('val', ''); } if (this.isInit) { self.$element.trigger($.Event('itemAddedOnInit', { item: item, options: options })); } else { self.$element.trigger($.Event('itemAdded', { item: item, options: options })); } }, /** * Removes the given item. Pass true to dontPushVal to prevent updating the * elements val() */ remove: function(item, dontPushVal, options) { var self = this; if (self.objectItems) { if (typeof item === "object") item = $.grep(self.itemsArray, function(other) { return self.options.itemValue(other) == self.options.itemValue(item); } ); else item = $.grep(self.itemsArray, function(other) { return self.options.itemValue(other) == item; } ); item = item[item.length-1]; } if (item) { var beforeItemRemoveEvent = $.Event('beforeItemRemove', { item: item, cancel: false, options: options }); self.$element.trigger(beforeItemRemoveEvent); if (beforeItemRemoveEvent.cancel) return; $('.badge', self.$container).filter(function() { return $(this).data('item') === item; }).remove(); $('option', self.$element).filter(function() { return $(this).data('item') === item; }).remove(); if($.inArray(item, self.itemsArray) !== -1) self.itemsArray.splice($.inArray(item, self.itemsArray), 1); } if (!dontPushVal) self.pushVal(self.options.triggerChange); // Remove class when reached maxTags if (self.options.maxTags > self.itemsArray.length) self.$container.removeClass('bootstrap-tagsinput-max'); self.$element.trigger($.Event('itemRemoved', { item: item, options: options })); }, /** * Removes all items */ removeAll: function() { var self = this; $('.badge', self.$container).remove(); $('option', self.$element).remove(); while(self.itemsArray.length > 0) self.itemsArray.pop(); self.pushVal(self.options.triggerChange); }, /** * Refreshes the tags so they match the text/value of their corresponding * item. */ refresh: function() { var self = this; $('.badge', self.$container).each(function() { var $tag = $(this), item = $tag.data('item'), itemValue = self.options.itemValue(item), itemText = self.options.itemText(item), tagClass = self.options.tagClass(item); // Update tag's class and inner text $tag.attr('class', null); $tag.addClass('badge ' + htmlEncode(tagClass)); $tag.contents().filter(function() { return this.nodeType == 3; })[0].nodeValue = htmlEncode(itemText); if (self.isSelect) { var option = $('option', self.$element).filter(function() { return $(this).data('item') === item; }); option.attr('value', itemValue); } }); }, /** * Returns the items added as tags */ items: function() { return this.itemsArray; }, /** * Assembly value by retrieving the value of each item, and set it on the * element. */ pushVal: function() { var self = this, val = $.map(self.items(), function(item) { return self.options.itemValue(item).toString(); }); self.$element.val(val, true); if (self.options.triggerChange) self.$element.trigger('change'); }, /** * Initializes the tags input behaviour on the element */ build: function(options) { var self = this; self.options = $.extend({}, defaultOptions, options); // When itemValue is set, freeInput should always be false if (self.objectItems) self.options.freeInput = false; makeOptionItemFunction(self.options, 'itemValue'); makeOptionItemFunction(self.options, 'itemText'); makeOptionFunction(self.options, 'tagClass'); // Typeahead Bootstrap version 2.3.2 if (self.options.typeahead) { var typeahead = self.options.typeahead || {}; makeOptionFunction(typeahead, 'source'); self.$input.typeahead($.extend({}, typeahead, { source: function (query, process) { function processItems(items) { var texts = []; for (var i = 0; i < items.length; i++) { var text = self.options.itemText(items[i]); map[text] = items[i]; texts.push(text); } process(texts); } this.map = {}; var map = this.map, data = typeahead.source(query); if ($.isFunction(data.success)) { // support for Angular callbacks data.success(processItems); } else if ($.isFunction(data.then)) { // support for Angular promises data.then(processItems); } else { // support for functions and jquery promises $.when(data) .then(processItems); } }, updater: function (text) { self.add(this.map[text]); return this.map[text]; }, matcher: function (text) { return (text.toLowerCase().indexOf(this.query.trim().toLowerCase()) !== -1); }, sorter: function (texts) { return texts.sort(); }, highlighter: function (text) { var regex = new RegExp( '(' + this.query + ')', 'gi' ); return text.replace( regex, "$1" ); } })); } // typeahead.js if (self.options.typeaheadjs) { // Determine if main configurations were passed or simply a dataset var typeaheadjs = self.options.typeaheadjs; if (!$.isArray(typeaheadjs)) { typeaheadjs = [null, typeaheadjs]; } $.fn.typeahead.apply(self.$input, typeaheadjs).on('typeahead:selected', $.proxy(function (obj, datum, name) { var index = 0; typeaheadjs.some(function(dataset, _index) { if (dataset.name === name) { index = _index; return true; } return false; }); // @TODO Dep: https://github.com/corejavascript/typeahead.js/issues/89 if (typeaheadjs[index].valueKey) { self.add(datum[typeaheadjs[index].valueKey]); } else { self.add(datum); } self.$input.typeahead('val', ''); }, self)); } self.$container.on('click', $.proxy(function(event) { if (! self.$element.attr('disabled')) { self.$input.removeAttr('disabled'); } self.$input.focus(); }, self)); if (self.options.addOnBlur && self.options.freeInput) { self.$input.on('focusout', $.proxy(function(event) { // HACK: only process on focusout when no typeahead opened, to // avoid adding the typeahead text as tag if ($('.typeahead, .twitter-typeahead', self.$container).length === 0) { self.add(self.$input.val()); self.$input.val(''); } }, self)); } // Toggle the 'focus' css class on the container when it has focus self.$container.on({ focusin: function() { self.$container.addClass(self.options.focusClass); }, focusout: function() { self.$container.removeClass(self.options.focusClass); }, }); self.$container.on('keydown', 'input', $.proxy(function(event) { var $input = $(event.target), $inputWrapper = self.findInputWrapper(); if (self.$element.attr('disabled')) { self.$input.attr('disabled', 'disabled'); return; } switch (event.which) { // BACKSPACE case 8: if (doGetCaretPosition($input[0]) === 0) { var prev = $inputWrapper.prev(); if (prev.length) { self.remove(prev.data('item')); } } break; // DELETE case 46: if (doGetCaretPosition($input[0]) === 0) { var next = $inputWrapper.next(); if (next.length) { self.remove(next.data('item')); } } break; // LEFT ARROW case 37: // Try to move the input before the previous tag var $prevTag = $inputWrapper.prev(); if ($input.val().length === 0 && $prevTag[0]) { $prevTag.before($inputWrapper); $input.focus(); } break; // RIGHT ARROW case 39: // Try to move the input after the next tag var $nextTag = $inputWrapper.next(); if ($input.val().length === 0 && $nextTag[0]) { $nextTag.after($inputWrapper); $input.focus(); } break; default: // ignore } // Reset internal input's size var textLength = $input.val().length, wordSpace = Math.ceil(textLength / 5), size = textLength + wordSpace + 1; $input.attr('size', Math.max(this.inputSize, size)); }, self)); self.$container.on('keypress', 'input', $.proxy(function(event) { var $input = $(event.target); if (self.$element.attr('disabled')) { self.$input.attr('disabled', 'disabled'); return; } var text = $input.val(), maxLengthReached = self.options.maxChars && text.length >= self.options.maxChars; if (self.options.freeInput && (keyCombinationInList(event, self.options.confirmKeys) || maxLengthReached)) { // Only attempt to add a tag if there is data in the field if (text.length !== 0) { self.add(maxLengthReached ? text.substr(0, self.options.maxChars) : text); $input.val(''); } // If the field is empty, let the event triggered fire as usual if (self.options.cancelConfirmKeysOnEmpty === false) { event.preventDefault(); } } // Reset internal input's size var textLength = $input.val().length, wordSpace = Math.ceil(textLength / 5), size = textLength + wordSpace + 1; $input.attr('size', Math.max(this.inputSize, size)); }, self)); // Remove icon clicked self.$container.on('click', '[data-role=remove]', $.proxy(function(event) { if (self.$element.attr('disabled')) { return; } self.remove($(event.target).closest('.badge').data('item')); }, self)); // Only add existing value as tags when using strings as tags if (self.options.itemValue === defaultOptions.itemValue) { if (self.$element[0].tagName === 'INPUT') { self.add(self.$element.val()); } else { $('option', self.$element).each(function() { self.add($(this).attr('value'), true); }); } } }, /** * Removes all tagsinput behaviour and unregsiter all event handlers */ destroy: function() { var self = this; // Unbind events self.$container.off('keypress', 'input'); self.$container.off('click', '[role=remove]'); self.$container.remove(); self.$element.removeData('tagsinput'); self.$element.show(); }, /** * Sets focus on the tagsinput */ focus: function() { this.$input.focus(); }, /** * Returns the internal input element */ input: function() { return this.$input; }, /** * Returns the element which is wrapped around the internal input. This * is normally the $container, but typeahead.js moves the $input element. */ findInputWrapper: function() { var elt = this.$input[0], container = this.$container[0]; while(elt && elt.parentNode !== container) elt = elt.parentNode; return $(elt); } }; /** * Register JQuery plugin */ $.fn.tagsinput = function(arg1, arg2, arg3) { var results = []; this.each(function() { var tagsinput = $(this).data('tagsinput'); // Initialize a new tags input if (!tagsinput) { tagsinput = new TagsInput(this, arg1); $(this).data('tagsinput', tagsinput); results.push(tagsinput); if (this.tagName === 'SELECT') { $('option', $(this)).attr('selected', 'selected'); } // Init tags from $(this).val() $(this).val($(this).val()); } else if (!arg1 && !arg2) { // tagsinput already exists // no function, trying to init results.push(tagsinput); } else if(tagsinput[arg1] !== undefined) { // Invoke function on existing tags input if(tagsinput[arg1].length === 3 && arg3 !== undefined){ var retVal = tagsinput[arg1](arg2, null, arg3); }else{ var retVal = tagsinput[arg1](arg2); } if (retVal !== undefined) results.push(retVal); } }); if ( typeof arg1 == 'string') { // Return the results from the invoked function calls return results.length > 1 ? results : results[0]; } else { return results; } }; $.fn.tagsinput.Constructor = TagsInput; /** * Most options support both a string or number as well as a function as * option value. This function makes sure that the option with the given * key in the given options is wrapped in a function */ function makeOptionItemFunction(options, key) { if (typeof options[key] !== 'function') { var propertyName = options[key]; options[key] = function(item) { return item[propertyName]; }; } } function makeOptionFunction(options, key) { if (typeof options[key] !== 'function') { var value = options[key]; options[key] = function() { return value; }; } } /** * HtmlEncodes the given value */ var htmlEncodeContainer = $(' '); function htmlEncode(value) { if (value) { return htmlEncodeContainer.text(value).html(); } else { return ''; } } /** * Returns the position of the caret in the given input field * http://flightschool.acylt.com/devnotes/caret-position-woes/ */ function doGetCaretPosition(oField) { var iCaretPos = 0; if (document.selection) { oField.focus (); var oSel = document.selection.createRange(); oSel.moveStart ('character', -oField.value.length); iCaretPos = oSel.text.length; } else if (oField.selectionStart || oField.selectionStart == '0') { iCaretPos = oField.selectionStart; } return (iCaretPos); } /** * Returns boolean indicates whether user has pressed an expected key combination. * @param object keyPressEvent: JavaScript event object, refer * http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html * @param object lookupList: expected key combinations, as in: * [13, {which: 188, shiftKey: true}] */ function keyCombinationInList(keyPressEvent, lookupList) { var found = false; $.each(lookupList, function (index, keyCombination) { if (typeof (keyCombination) === 'number' && keyPressEvent.which === keyCombination) { found = true; return false; } if (keyPressEvent.which === keyCombination.which) { var alt = !keyCombination.hasOwnProperty('altKey') || keyPressEvent.altKey === keyCombination.altKey, shift = !keyCombination.hasOwnProperty('shiftKey') || keyPressEvent.shiftKey === keyCombination.shiftKey, ctrl = !keyCombination.hasOwnProperty('ctrlKey') || keyPressEvent.ctrlKey === keyCombination.ctrlKey; if (alt && shift && ctrl) { found = true; return false; } } }); return found; } /** * Initialize tagsinput behaviour on inputs and selects which have * data-role=tagsinput * zmm2113@qq.com 2018.6.24 */ $(function() { $("input[data-role=tagsinput], select[multiple][data-role=tagsinput]").tagsinput(); }); })(window.jQuery);
jquery实现文本框选择器_商品尺寸选择和商品
前几天看到有人在一个群里问如何实现商品规格选择并显示价格，多的不少，直接上代码：一、带图文版本1.所需要用到的jQuery文件 2.用的CSS代码@charset "utf-8"; /* CSS Document */ *{ margin:0; padding:0;-webkit-text-size-adjust:none;} body{ background:#fff; font-size:12px; color:#555; font-family:Tahoma, Geneva, sans-serif; padding:100px 100px;} a{ color:#555; text-decoration:none;} a:hover{ color:#c00; text-decoration:underline;} img{ border:none;} li{ list-style:none;} .clearfix:after {visibility: hidden;display: block;font-size: 0;content: " ";clear: both;height: 0;} * html .clearfix { zoom: 1; } /* IE6 */ *:first-child+html .clearfix { zoom: 1; } /* IE7 */ /*tab*/ .tab{ line-height:56px; font-size:14px;} .tab a{ color:#07c;} .tab a:hover{ color:#c00;} .tab a.cur{ font-weight:bold;} /*商品详细页*/ /*iteminfo*/ .iteminfo{} .iteminfo_tit{ color:#333; font-size:22px; font-family:"微软雅黑",Arial, Helvetica, sans-serif; border-bottom:1px solid #e3e3e3; font-weight:normal; padding-bottom:12px; line-height:32px;} .iteminfo_parameter{ padding:8px 0; padding-left:70px;} .iteminfo_parameter_default{ color:#888;} .iteminfo_parameter dt{ margin-left:-70px; float:left; display:inline; width:60px; white-space:nowrap; text-align:right; color:#888;} .iteminfo_mktprice{ font-size:12px; font-family:Arial, Helvetica, sans-serif; text-decoration:line-through;} .lh32{ line-height:32px;} .iteminfo_price{ color:#c00; font-size:14px; font-family:Arial, Helvetica, sans-serif; vertical-align:middle;} .sys_item_price{ color:#c00; font-size:22px; vertical-align:middle;} .iteminfo_buying{ background:#f7f7f7; padding:12px 0;} /*规格*/ .sys_item_spec dl.iteminfo_parameter{ padding-top:5px; padding-bottom:5px;} .sys_item_spec dl.iteminfo_parameter dt{ line-height:32px;} /*一下正对图片*/ .sys_spec_img{} .sys_spec_img li{ float:left; height:54px; position:relative; margin:2px 6px 2px 0;} .sys_spec_img li a{height:50px; width:50px; padding:1px; border:1px solid #ccc; float:left; background:#fff; display:inline-block; outline:none;} .sys_spec_img li a img{ width:50px; height:50px; display:block;} .sys_spec_img li a:hover{ border:2px solid #e4393c; padding:0; text-decoration:none;} .sys_spec_img li i{ position:absolute; width:10px; height:10px; font-size:0; line-height:0; right:2px; bottom:2px; background:url(img/sys_item_selected.gif) no-repeat right bottom; z-index:99; display:none;} .sys_spec_img li.selected a{ border:2px solid #e4393c; padding:0;} .sys_spec_img li.selected i{ display:block;} .sys_spec_text{} .sys_spec_text li{ float:left; height:28px; position:relative; margin:2px 6px 2px 0; outline:none;} .sys_spec_text li a{ height:24px; padding:1px 6px; border:1px solid #ccc; background:#fff; display:inline-block; line-height:24px;} .sys_spec_text li a:hover{ border:2px solid #e4393c; padding:0 5px; text-decoration:none;} .sys_spec_text li i{ position:absolute; width:10px; height:10px; font-size:0; line-height:0; right:2px; bottom:2px; background:url(img/sys_item_selected.gif) no-repeat right bottom; z-index:99; display:none;} .sys_spec_text li.selected a{ border:2px solid #e4393c; padding:0 5px;} .sys_spec_text li.selected i{ display:block;}3.界面布局 带图片选择 纯文本选择 市场价 $13.00 本网价 $ 6.80 颜色 尺码 S M L XL 4.核心实现代码： 效果图一：二、无图片（纯文本）版本1.所需要用到的jQuery文件 2.用的CSS代码@charset "utf-8"; /* CSS Document */ *{ margin:0; padding:0;-webkit-text-size-adjust:none;} body{ background:#fff; font-size:12px; color:#555; font-family:Tahoma, Geneva, sans-serif; padding:100px 100px;} a{ color:#555; text-decoration:none;} a:hover{ color:#c00; text-decoration:underline;} img{ border:none;} li{ list-style:none;} .clearfix:after {visibility: hidden;display: block;font-size: 0;content: " ";clear: both;height: 0;} * html .clearfix { zoom: 1; } /* IE6 */ *:first-child+html .clearfix { zoom: 1; } /* IE7 */ /*tab*/ .tab{ line-height:56px; font-size:14px;} .tab a{ color:#07c;} .tab a:hover{ color:#c00;} .tab a.cur{ font-weight:bold;} /*商品详细页*/ /*iteminfo*/ .iteminfo{} .iteminfo_tit{ color:#333; font-size:22px; font-family:"微软雅黑",Arial, Helvetica, sans-serif; border-bottom:1px solid #e3e3e3; font-weight:normal; padding-bottom:12px; line-height:32px;} .iteminfo_parameter{ padding:8px 0; padding-left:70px;} .iteminfo_parameter_default{ color:#888;} .iteminfo_parameter dt{ margin-left:-70px; float:left; display:inline; width:60px; white-space:nowrap; text-align:right; color:#888;} .iteminfo_mktprice{ font-size:12px; font-family:Arial, Helvetica, sans-serif; text-decoration:line-through;} .lh32{ line-height:32px;} .iteminfo_price{ color:#c00; font-size:14px; font-family:Arial, Helvetica, sans-serif; vertical-align:middle;} .sys_item_price{ color:#c00; font-size:22px; vertical-align:middle;} .iteminfo_buying{ background:#f7f7f7; padding:12px 0;} /*规格*/ .sys_item_spec dl.iteminfo_parameter{ padding-top:5px; padding-bottom:5px;} .sys_item_spec dl.iteminfo_parameter dt{ line-height:32px;} /*一下正对图片*/ .sys_spec_img{} .sys_spec_img li{ float:left; height:54px; position:relative; margin:2px 6px 2px 0;} .sys_spec_img li a{height:50px; width:50px; padding:1px; border:1px solid #ccc; float:left; background:#fff; display:inline-block; outline:none;} .sys_spec_img li a img{ width:50px; height:50px; display:block;} .sys_spec_img li a:hover{ border:2px solid #e4393c; padding:0; text-decoration:none;} .sys_spec_img li i{ position:absolute; width:10px; height:10px; font-size:0; line-height:0; right:2px; bottom:2px; background:url(img/sys_item_selected.gif) no-repeat right bottom; z-index:99; display:none;} .sys_spec_img li.selected a{ border:2px solid #e4393c; padding:0;} .sys_spec_img li.selected i{ display:block;} .sys_spec_text{} .sys_spec_text li{ float:left; height:28px; position:relative; margin:2px 6px 2px 0; outline:none;} .sys_spec_text li a{ height:24px; padding:1px 6px; border:1px solid #ccc; background:#fff; display:inline-block; line-height:24px;} .sys_spec_text li a:hover{ border:2px solid #e4393c; padding:0 5px; text-decoration:none;} .sys_spec_text li i{ position:absolute; width:10px; height:10px; font-size:0; line-height:0; right:2px; bottom:2px; background:url(img/sys_item_selected.gif) no-repeat right bottom; z-index:99; display:none;} .sys_spec_text li.selected a{ border:2px solid #e4393c; padding:0 5px;} .sys_spec_text li.selected i{ display:block;}3.界面布局 带图片选择 纯文本选择 市场价 $13.00 本网价 $ 6.80 颜色 白色 粉色 蓝色 绿色 黄色 灰色 尺码 S M L XL 4.核心实现代码： 效果图二：上就是本文的全部内容，希望对大家的学习有所帮助，也希望大家多多支持轩宇网。
这篇文章主要为大家详细介绍了js实现页面多个日期时间倒计时效果，具有一定的参考价值，感兴趣的小伙伴们可以参考一下js的日期倒计时在日常项目中还是比较常用的，活动、拼团功能最为常见，先分析最要是处理好日期函数，然后一个页面上有多个倒计时情况下的方法；来，先看下 拼多多 的拼单倒计时的效果：那么，先上个代码吧：页面布局代码： 时间1 时间2 时间3 时间4 时间5 CSS样式代码： 方法一： 方法二： 完整代码： js拼团日期倒计时 时间1 时间2 时间3 时间4 时间5 案例效果：以上就是本文的全部内容，希望对大家的学习有所帮助，也希望大家多多支持轩宇网。原文链接：https://blog.csdn.net/weixin_42211816/article/details/88871407
实现n秒倒计时后才可以点击的效果
这篇文章主要介绍了js点击按钮在倒计时后才可以点击的效果,需要的朋友可以参考下在我们进行注册用户时经常遇到点击按钮后，60秒倒计时后才能继续可以点击，按钮上还能显示倒计时，这60秒时间就是为大家提供”细阅读协议“做准备的，这种功能是如何实现的，下面为大家分享详细代码。 倒计时然后才可以点击效果代码 注册协议 希望本文所述对大家学习javascript程序设计有所帮助。另外附上使用jquery实现倒计时可点击A链接功能源码 倒數 效果图：
JavaScript 数组排序（从大到小，从小到大）及将两个一维数组组合成一个二维数组并保持其中一个数组不变，且第一个数组的key值对应第二个数组的值1、数组的从大到小排序//创建数组元素arr var arr=[7,13,34,3,200,100,4]; //创建每次循环存储最大值得变量 var max; //遍历数组，默认arr中的某一个元素为最大值，进行逐一比较 for(var i=0; i<arr.length; i++){ //外层循环一次，就拿arr[i] 和 内层循环arr.legend次的 arr[j] 做对比 for(var j=i; j<arr.length; j++){ if(arr[i]<arr[j]){ //如果arr[j]大就把此时的值赋值给最大值变量max max=arr[j]; arr[j]=arr[i]; arr[i]=max; } } } document.write(arr.toString()+" "); //200,100,34,13,7,4,32、数组的从小到大排序。var Arr=[13,7,10,76,97,100,35]; var min; for(var i=0; i<Arr.length; i++){ for(var j=i; j<Arr.length;j++){ if(Arr[i]>Arr[j]){ min=Arr[j]; Arr[j]=Arr[i]; Arr[i]=min; } } } document.write(Arr.toString()+" "); //7,10,13,35,76,97,1003、综合应用（将两个一维数组组合成一个二维数组并保持其中一个数组不变，且第一个数组的key值对应第二个数组的值） var array1 = [5,9,3,8]; var max; //遍历数组，默认arr中的某一个元素为最大值，进行逐一比较 for(var i=0; i<array1.length; i++){ //外层循环一次，就拿arr[i] 和 内层循环arr.legend次的 arr[j] 做对比 for(var j=i; j<array1.length; j++){ if(array1[i]<array1[j]){ //如果arr[j]大就把此时的值赋值给最大值变量max max=array1[j]; array1[j]=array1[i]; array1[i]=max; } } } console.log(array1); var array2 = [0,6,2,3]; var arrd = array1.map((item, idx) => [item, array2[idx]]); //document.write(arrd); document.write(arrd); //document.write(arrd[2]); console.log(arrd);
这是一个典型的Ajax应用，在页面上，您只需要点击“下一页”，数据区将自动加载对应页码的数据，重新刷新数据区。类似的效果在很多网站上应用，尤其在一些需要展示大量图片数据的网页如淘宝商品列表页，Ajax分页效果让您的网站数据加载显得非常流畅。HTML 页面中，list用来展示数据列表，包括本例要展示的商品图片和标题，pagecount用来展示分页条，即本例中的上一页、下一页。当然，别忘了，在head中预先载入jquery库文件。CSS我们需要将商品图片进行排列，以及设置分页条样式，当然这些样式的设计可以根据读取成功后的数据进行设置，本例中我们先把css代码贴出来。#list{width:680px; height:530px; margin:2px auto; position:relative} #list ul li{float:left;width:220px; height:260px; margin:2px} #list ul li img{width:220px; height:220px} #list ul li p{line-height:22px} #pagecount{width:500px; margin:10px auto; text-align:center} #pagecount span{margin:4px; font-size:14px} #list ul li#loading{width:120px; height:32px; border:1px solid #d3d3d3; position:absolute; top:35%; left:42%; text-align:center; background:#f7f7f7 url(loading.gif) no-repeat 8px 8px;-moz-box-shadow:1px 1px 2px rgba(0,0,0,.2); -webkit-box-shadow:1px 1px 2px rgba(0,0,0,.2); box-shadow:1px 1px 2px rgba(0,0,0,.2);} 我们先声明变量，后面的代码要用到以下变量。var curPage = 1; //当前页码 var total,pageSize,totalPage; //总记录数，每页显示数，总页数 接下来，我们自定义一个函数：getData()，用来获取当前页数据。函数中，我们利用$.ajax()向后台pages.php发送POST异步请求，将当前页码以JSON格式传递给后台。//获取数据 function getData(page){ $.ajax({ type: 'POST', url: 'pages.php', data: {'pageNum':page-1}, dataType:'json', beforeSend:function(){ $("#list ul").append(" loading... ");//显示加载动画 }, success:function(json){ $("#list ul").empty();//清空数据区 total = json.total; //总记录数 pageSize = json.pageSize; //每页显示条数 curPage = page; //当前页 totalPage = json.totalPage; //总页数 var li = ""; var list = json.list; $.each(list,function(index,array){ //遍历json数据列 li += " "+array['title'] +" "; }); $("#list ul").append(li); }, complete:function(){ //生成分页条 getPageBar(); }, error:function(){ alert("数据加载失败"); } }); } 请求成功后并返回数据，将相应的数据附给变量，并将返回的商品数据列表循环展示到对应容器#list ul中。当数据完全加载完毕后，调用分页条函数getPageBar()生成分页条。//获取分页条 function getPageBar(){ //页码大于最大页数 if(curPage>totalPage) curPage=totalPage; //页码小于1 if(curPage<1) curPage=1; pageStr = "共"+total+"条"+curPage +"/"+totalPage+""; //如果是第一页 if(curPage==1){ pageStr += "首页上一页"; }else{ pageStr += "首页 上一页"; } //如果是最后页 if(curPage>=totalPage){ pageStr += "下一页尾页"; }else{ pageStr += " 下一页尾页 "; } $("#pagecount").html(pageStr); } 最后，当页面第一次加载时，我们加载第一页数据即getData(1)，当点击分页条中的分页链接时，调用getData(page)加载对应页码的数据。我们通过getPageBar()函数已预先在翻页连接的属性rel中在埋入了数字页码。$(function(){ getData(1); $("#pagecount span a").live('click',function(){ var rel = $(this).attr("rel"); if(rel){ getData(rel); } }); }); PHPpages.php接收每次前端页面的ajax请求，根据提交的页码pageNum值，从mysql数据库中获取数据，计算总记录数和总页数，读取对应页码下的数据列表，并将最终结果以JSON格式返回给前端页面。<?php header("Content-Type: text/html;charset=utf-8"); //error_reporting(E_ALL); //ini_set('display_errors', true); date_default_timezone_set("PRC"); //系统使用北京时间 define('DBHOST', 'localhost'); define('DBNAME', 'demo'); define('DBUSER', 'root'); define('DBPWD', ''); define('DBPREFIX', 'hw_'); define('DBCHARSET', 'utf8'); define('CONN', ''); define('TIMEZONE', 'Asia/Shanghai'); try{ $db = new PDO('mysql:host='.DBHOST.';dbname='.DBNAME, DBUSER, DBPWD); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db->query('SET NAMES utf8;'); }catch(PDOException $e ){ echo "Error: ".$e; } $page = intval($_POST['pageNum']); $sql = "SELECT count(*) as tt FROM `food`"; $stmt = $db->query($sql); $stmt->execute(); $rs = $stmt->fetch(PDO::FETCH_ASSOC); $total = $rs['tt']; $pageSize = 6; //每页显示数 $totalPage = ceil($total/$pageSize); //总页数 $startPage = $page*$pageSize;//开始记录 //构造数组 $arr['total'] = $total; $arr['pageSize'] = $pageSize; $arr['totalPage'] = $totalPage; $sql = "select id,title,pic from food order by id asc limit $startPage,$pageSize";//查询分页数据 $stmt = $db->query($sql); $stmt->execute(); $list = $stmt->fetchAll(PDO::FETCH_ASSOC); foreach ($list as $key => $val) { $arr['list'][] = array( 'id' => $val['id'], 'title' => $val['title'], 'pic' => $val['pic'], ); } //print_r($arr); echo json_encode($arr);//输出json数据这时再回到前端页面，即看到数据已分号页，点击“下一页”看看是不是你要的效果，查看DEMO，分页条的样式大家可以自己定制，我给的是最基本的样式。最后，附上Mysql表结构，下载源码包中带数据表哦，^-^都为您准备好了。CREATE TABLE IF NOT EXISTS `food` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(100) NOT NULL, `pic` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;以上就是关于jQuery+Ajax+PHP+Mysql实现分页显示数据实例讲解，Ajax分页效果让您的网站数据加载显得非常流畅，希望这篇文章对大家的学习有所帮助。最后源码下载： helloweba_pages.rar 原文链接：https://www.helloweba.net/javascript/195.html
微信小程序实现商品属性联动选择
这篇文章主要为大家详细介绍了微信小程序实现商品属性联动选择，具有一定的参考价值，感兴趣的小伙伴们可以参考一下先上个效果图，效果演示：代码示例1、commodity.xml<!-- <view class="title">属性值联动选择</view> --> <view class="commodity_attr_list"> <view class="attr_box" wx:for="{{attrValueList}}" wx:for-item="attrValueObj" wx:for-index="attrIndex"> <view class="attr_name">{{attrValueObj.attrKey}}</view> <view class="attr_value_box"> <view class="attr_value " bindtap="selectAttrValue" data-status="{{attrValueObj.attrValueStatus[valueIndex]}}" data-value="{{value}}" data-key="{{attrValueObj.attrKey}}" data-code="{{attrCode}}" data-index="{{attrIndex}}" data-selectedvalue="{{attrValueObj.selectedValue}}" wx:for="{{attrValueObj.attrValues}}" wx:for-item="value" wx:for-index="valueIndex">{{value}}</view> </view> </view> </view> <view class="weui-btn-area"> 选好了 </view>上述代码把页面盒子分为两部分commodity_attr_list和weui-btn-area。 commodity_attr_list：循环获取商品的属性名和相对应的属性值，并布局页面。 weui-btn-area：提交校验并获取选中商品属性结果。2、commodity.js数据结构//数据结构：以一组一组的数据来进行设定 commodityAttr: [ { priceId: 1, price: 35.0, "stock": 8, "attrValueList": [ { "attrKey": "规格：", "attrValue": "+免费配料", "attrCode": "1001" }, { "attrKey": "甜度：", "attrValue": "七分甜", "attrCode": "2001" }, { "attrKey": "加料：", "attrValue": "珍珠", "attrCode": "3001" }, { "attrKey": "冰块：", "attrValue": "少冰", "attrCode": "4001" } ] }, { priceId: 2, price: 35.1, "stock": 9, "attrValueList": [ { "attrKey": "规格：", "attrValue": "+燕麦", "attrCode": "1002" }, { "attrKey": "甜度：", "attrValue": "五分甜", "attrCode": "2002" }, { "attrKey": "加料：", "attrValue": "椰果", "attrCode": "3002" }, { "attrKey": "冰块：", "attrValue": "去冰", "attrCode": "4002" } ] }, { priceId: 3, price: 35.2, "stock": 10, "attrValueList": [ { "attrKey": "规格：", "attrValue": "+布丁", "attrCode": "1003" }, { "attrKey": "甜度：", "attrValue": "无糖", "attrCode": "2003" }, { "attrKey": "加料：", "attrValue": "仙草", "attrCode": "3003" }, { "attrKey": "冰块：", "attrValue": "常温", "attrCode": "4003" } ] }, { priceId: 4, price: 35.2, "stock": 10, "attrValueList": [ { "attrKey": "规格：", "attrValue": "再加一份奶霜", "attrCode": "1004" }, { "attrKey": "甜度：", "attrValue": "无糖", "attrCode": "2003" }, { "attrKey": "加料：", "attrValue": "仙草", "attrCode": "3004" }, { "attrKey": "冰块：", "attrValue": "热饮", "attrCode": "4004" } ] }, { priceId: 5, price: 35.2, "stock": 10, "attrValueList": [ { "attrKey": "规格：", "attrValue": "+免费配料", "attrCode": "1004" }, { "attrKey": "甜度：", "attrValue": "五分甜", "attrCode": "2003" }, { "attrKey": "加料：", "attrValue": "椰果", "attrCode": "3004" }, { "attrKey": "冰块：", "attrValue": "常温", "attrCode": "4004" } ] } ], attrValueList: [] }属性选中和取消选择效果处理 onShow: function () { this.setData({ includeGroup: this.data.commodityAttr }); this.distachAttrValue(this.data.commodityAttr); // 只有一个属性组合的时候默认选中 // console.log(this.data.attrValueList); if (this.data.commodityAttr.length == 1) { for (var i = 0; i < this.data.commodityAttr[0].attrValueList.length; i++) { this.data.attrValueList[i].selectedValue = this.data.commodityAttr[0].attrValueList[i].attrValue; } this.setData({ attrValueList: this.data.attrValueList }); } }, /* 获取数据 */ distachAttrValue: function (commodityAttr) { /** 将后台返回的数据组合成类似 { attrKey:'型号', attrValueList:['1','2','3'] } */ // 把数据对象的数据（视图使用），写到局部内 var attrValueList = this.data.attrValueList; // 遍历获取的数据 for (var i = 0; i < commodityAttr.length; i++) { for (var j = 0; j < commodityAttr[i].attrValueList.length; j++) { var attrIndex = this.getAttrIndex(commodityAttr[i].attrValueList[j].attrKey, attrValueList); // console.log('属性索引', attrIndex); // 如果还没有属性索引为-1，此时新增属性并设置属性值数组的第一个值；索引大于等于0，表示已存在的属性名的位置 if (attrIndex >= 0) { // 如果属性值数组中没有该值，push新值；否则不处理 if (!this.isValueExist(commodityAttr[i].attrValueList[j].attrValue, attrValueList[attrIndex].attrValues)) { attrValueList[attrIndex].attrValues.push(commodityAttr[i].attrValueList[j].attrValue); } } else { attrValueList.push({ attrKey: commodityAttr[i].attrValueList[j].attrKey, attrValues: [commodityAttr[i].attrValueList[j].attrValue] }); } } } // console.log('result', attrValueList) for (var i = 0; i < attrValueList.length; i++) { for (var j = 0; j < attrValueList[i].attrValues.length; j++) { if (attrValueList[i].attrValueStatus) { attrValueList[i].attrValueStatus[j] = true; } else { attrValueList[i].attrValueStatus = []; attrValueList[i].attrValueStatus[j] = true; } } } this.setData({ attrValueList: attrValueList }); }, getAttrIndex: function (attrName, attrValueList) { // 判断数组中的attrKey是否有该属性值 for (var i = 0; i < attrValueList.length; i++) { if (attrName == attrValueList[i].attrKey) { break; } } return i < attrValueList.length ? i : -1; }, isValueExist: function (value, valueArr) { // 判断是否已有属性值 for (var i = 0; i < valueArr.length; i++) { if (valueArr[i] == value) { break; } } return i < valueArr.length; }, /* 选择属性值事件 */ selectAttrValue: function (e) { /* 点选属性值，联动判断其他属性值是否可选 { attrKey:'型号', attrValueList:['1','2','3'], selectedValue:'1', attrValueStatus:[true,true,true] } console.log(e.currentTarget.dataset); */ var attrValueList = this.data.attrValueList; var index = e.currentTarget.dataset.index;//属性索引 var key = e.currentTarget.dataset.key; var value = e.currentTarget.dataset.value; if (e.currentTarget.dataset.status || index == this.data.firstIndex) { if (e.currentTarget.dataset.selectedvalue == e.currentTarget.dataset.value) { // 取消选中 this.disSelectValue(attrValueList, index, key, value); } else { // 选中 this.selectValue(attrValueList, index, key, value); } } }, /* 选中 */ selectValue: function (attrValueList, index, key, value, unselectStatus) { // console.log('firstIndex', this.data.firstIndex); var includeGroup = []; if (index == this.data.firstIndex && !unselectStatus) { // 如果是第一个选中的属性值，则该属性所有值可选 var commodityAttr = this.data.commodityAttr; // 其他选中的属性值全都置空 // console.log('其他选中的属性值全都置空', index, this.data.firstIndex, !unselectStatus); for (var i = 0; i < attrValueList.length; i++) { for (var j = 0; j < attrValueList[i].attrValues.length; j++) { attrValueList[i].selectedValue = ''; } } } else { var commodityAttr = this.data.includeGroup; } // console.log('选中', commodityAttr, index, key, value); for (var i = 0; i < commodityAttr.length; i++) { for (var j = 0; j < commodityAttr[i].attrValueList.length; j++) { if (commodityAttr[i].attrValueList[j].attrKey == key && commodityAttr[i].attrValueList[j].attrValue == value) { includeGroup.push(commodityAttr[i]); } } } attrValueList[index].selectedValue = value; // 判断属性是否可选 for (var i = 0; i < attrValueList.length; i++) { for (var j = 0; j < attrValueList[i].attrValues.length; j++) { attrValueList[i].attrValueStatus[j] = false; } } for (var k = 0; k < attrValueList.length; k++) { for (var i = 0; i < includeGroup.length; i++) { for (var j = 0; j < includeGroup[i].attrValueList.length; j++) { if (attrValueList[k].attrKey == includeGroup[i].attrValueList[j].attrKey) { for (var m = 0; m < attrValueList[k].attrValues.length; m++) { if (attrValueList[k].attrValues[m] == includeGroup[i].attrValueList[j].attrValue) { attrValueList[k].attrValueStatus[m] = true; } } } } } } // console.log('结果', attrValueList); this.setData({ attrValueList: attrValueList, includeGroup: includeGroup }); var count = 0; for (var i = 0; i < attrValueList.length; i++) { for (var j = 0; j < attrValueList[i].attrValues.length; j++) { if (attrValueList[i].selectedValue) { count++; break; } } } if (count < 2) {// 第一次选中，同属性的值都可选 this.setData({ firstIndex: index }); } else { this.setData({ firstIndex: -1 }); } }, /* 取消选中 */ disSelectValue: function (attrValueList, index, key, value) { var commodityAttr = this.data.commodityAttr; attrValueList[index].selectedValue = ''; // 判断属性是否可选 for (var i = 0; i < attrValueList.length; i++) { for (var j = 0; j < attrValueList[i].attrValues.length; j++) { attrValueList[i].attrValueStatus[j] = true; } } this.setData({ includeGroup: commodityAttr, attrValueList: attrValueList }); for (var i = 0; i < attrValueList.length; i++) { if (attrValueList[i].selectedValue) { this.selectValue(attrValueList, i, attrValueList[i].attrKey, attrValueList[i].selectedValue, true); } } } 结果提交submit: function () { var value = []; for (var i = 0; i < this.data.attrValueList.length; i++) { if (!this.data.attrValueList[i].selectedValue) { break; } value.push(this.data.attrValueList[i].selectedValue); } if (i < this.data.attrValueList.length) { wx.showToast({ title: '请选择完整！', icon: 'loading', duration: 1000 }) } else { var valueStr = ""; for(var i = 0;i < value.length;i++){ console.log(value[i]); valueStr += value[i]+","; } wx.showModal({ title: '提示', content: valueStr, success: function (res) { if (res.confirm) { console.log('用户点击确定') } else if (res.cancel) { console.log('用户点击取消') } } }) console.log(valueStr); } }3、commodity.wxss.title { padding: 10rpx 20rpx; margin: 10rpx 0; border-left: 4rpx solid #ccc; } /*全部属性的主盒子*/ .commodity_attr_list { background: #fff; padding: 0 20rpx; font-size: 26rpx; overflow: hidden; width: 100%; } /*每组属性的主盒子*/ .attr_box { width: 100%; overflow: hidden; border-bottom: 1rpx solid #ececec; display: flex; flex-direction: column; } /*属性名*/ .attr_name { width: 20%; float: left; padding: 15rpx 0; } /*属性值*/ .attr_value_box { width: 80%; float: left; padding: 15rpx 0; overflow: hidden; } /*每个属性值*/ .attr_value { float: left; padding: 0 30rpx; margin: 10rpx 10rpx; border: 1rpx solid #ececec; border-radius:5px; line-height:30px; } /*每个属性选中的当前样式*/ .attr_value_active { border-radius: 10rpx; color: #0089dc; padding: 0 30rpx; border: 1rpx solid #0089dc; /* background: #fff; */ } /*禁用属性*/ .attr_value_disabled { color: #ccc; } /*button*/ .weui-btn-area { margin: 1.17647059em 15px 0.3em; } .weui-btn{ width: 80%; height: 100rpx; border-radius: 3rpx; background-color:#0089dc; color: #fff; }好了，复制上述代码就可以实现效果哦，赶紧试试吧！以上就是本文的全部内容，希望对大家的学习有所帮助，也希望大家多多支持轩宇网。原文链接：https://blog.csdn.net/qq_36150631/article/details/83272161
这篇文章主要介绍了PHP+MySQL实现的三级联动菜单功能,涉及mysql数据库创建、数据添加及php读取mysql、创建联动菜单相关操作技巧,需要的朋友可以参考下数据库mysql-- 数据库: `student` -- -- -------------------------------------------------------- -- -- 表的结构 `student` -- CREATE TABLE `student` ( `id` int(50) NOT NULL auto_increment, `name` varchar(50) collate utf8_unicode_ci NOT NULL, `dept` varchar(50) collate utf8_unicode_ci NOT NULL, `class` varchar(50) collate utf8_unicode_ci NOT NULL, `sex` varchar(50) collate utf8_unicode_ci NOT NULL, `dept_id` int(50) NOT NULL, `class_id` int(50) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=5 ; -- -- 导出表中的数据 `student` -- INSERT INTO `student` (`id`, `name`, `dept`, `class`, `sex`, `dept_id`, `class_id`) VALUES (1, '计算机名字', '计算机工程系', '计061', '男', 1, 11), (2, '教计名字', '计算机工程系', '教技061', '男', 1, 14), (3, '管理名字', '管理系', '管理061', '女', 2, 21), (4, '机械名字', '机械工程系', '自动化061', '男', 3, 31); index.php代码：<?php $link=mysql_connect("localhost","root","") or die("数据库服务器连接错误".mysql_error()); mysql_select_db("student",$link) or die("数据库访问错误".mysql_error()); mysql_query("set character set gb2312"); mysql_query("set names gb2312"); ?> 下拉框连动 三级联动演示： --请选择-- 计算机工程系 管理系 机械工程系 --请选择-- --请选择--
本文主要介绍使用jQuery+PHP+MySQL实现星际评论在美团、淘宝、京东等网页上，有许多商品、服务评价页面，五星好评功能很常见，本文利用jQuery实现五星好评功能。一、页面布局代码： 二、页面样式代码： 三、jquery代码引入jquery ajax传输代码（核心代码） 四、用到的PHP文件代码ajax.php <?php /** * @处理评分 */ include_once ('connect.php'); $score = $_POST['score']; if (isset($score)) { $cookiestr = getip(); $time = time(); if (isset($_COOKIE['person']) && $_COOKIE['person'] == $cookiestr) { echo "1"; } elseif (isset($_COOKIE['rate_time']) && ($time - intval($_COOKIE['rate_time'])) < 60) { echo "2"; } else { $query = mysql_query("update raty set voter=voter+1,total=total+'$score' where id=1"); $query = mysql_query("select * from raty where id=1"); $rs = mysql_fetch_array($query); $aver = 0; if ($rs) { $aver = $rs['total'] / $rs['voter']; $aver = round($aver, 1) * 10; } //设置COOKIE setcookie("person", $cookiestr, time() + 3600 * 365); setcookie("rate_time", time(), time() + 3600 * 365); echo $aver; } } function getip() { if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) { $ip = getenv("HTTP_CLIENT_IP"); } else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) { $ip = getenv("HTTP_X_FORWARDED_FOR"); } else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) { $ip = getenv("REMOTE_ADDR"); } else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) { $ip = $_SERVER['REMOTE_ADDR']; } else { $ip = "unknown"; } return ($ip); } ?> connect.php<?php /** * @数据库链接 */ $host="localhost"; $db_user="root"; $db_pass="123456"; $db_name="demo"; $timezone="Asia/Shanghai"; $link=mysql_connect($host,$db_user,$db_pass); mysql_select_db($db_name,$link); mysql_query("SET names UTF8"); header("Content-Type: text/html; charset=utf-8"); ?>五、数据库表结构raty表结构CREATE TABLE IF NOT EXISTS `raty` ( `id` int(11) NOT NULL AUTO_INCREMENT, `voter` int(10) NOT NULL DEFAULT '0' COMMENT '评分次数', `total` int(11) NOT NULL DEFAULT '0' COMMENT '总分', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;六、用到素材直接另存为star.gif保存到运行目录下的images下即可七、运行效果：