点击<select>的选项跳到相应网页

本文介绍如何通过JavaScript操作HTML元素实现网页间的导航与自动跳转,具体展示了使用getElementById和onchange事件来实现从百度、淘宝、优快云等网站间的无缝切换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<select id="d1">
		<option value="http://www.baidu.com/">百度</option>
		<option value="http://www.taobao.com/">淘宝</option>
		<option value="http://www.youkuaiyun.com/">优快云</option>
	</select>

 var d1=document.getElementById("d1");
        d1.onchange=function(){
        	window.location.href=this.value;
        }

以下2頁面代碼修改,比照顯示病態名稱及啟動病態關聯器等相關功能為範例,增加顯示本草名稱(欄位為mntag,位置為MNTag/?format=json,對應其中mnname中的字串)與啟動本草關聯器(位置為MRMN/?format=json)等相關功能, mrviewer.vue: <template> <div class="container"> <!-- 控制面板 --> <div class="control-panel"> <button @click="fetchData" class="refresh-btn">刷新數據</button> <button @click="toggleRelative" class="relative-btn"> {{ showRelative ? '關閉病態關聯器' : '啟動病態關聯器' }} </button> <input v-model="searchQuery" placeholder="搜索..." class="search-input" /> <div class="pagination-controls"> <span>每頁顯示:</span> <select v-model.number="pageSize" class="page-size-select"> <option value="1">1筆</option> <option value="4">4筆</option> <option value="10">10筆</option> </select> <button @click="prevPage" :disabled="currentPage === 1">上一页</button> <span>第</span> <input type="number" v-model.number="inputPage" min="1" :max="totalPages" class="page-input" @input="handlePageInput"> <span>頁 / 共 {{ totalPages }} 頁</span> <button @click="nextPage" :disabled="currentPage === totalPages">下一頁</button> <span>醫案閱讀器</span> </div> </div> <!-- 主内容区域 --> <div class="content-area"> <div class="horizontal-records" v-if="filteredData.length > 0"> <div v-for="(item, index) in paginatedData" :key="item.id" class="record-card"> <div class="record-header"> <h3>醫案 #{{ (currentPage - 1) * pageSize + index + 1 }}</h3> </div> <div class="record-body"> <div v-for="(value, key) in processFieldNames(item)" :key="key" class="record-field"> <div class="field-name">{{ key }}:</div> <div class="field-value"> <div v-if="key === '病態名稱' && Array.isArray(value)" class="dntag-value"> {{ formatDntagValue(value) }} </div> <div v-else-if="Array.isArray(value)" class="array-value"> <span v-for="(subItem, subIndex) in value" :key="subIndex"> <span v-html="formatValue(subItem, key)"></span><span v-if="subIndex < value.length - 1">;</span> </span> </div> <div v-else v-html="formatValue(value, key)"></div> </div> </div> </div> </div> </div> <div v-else class="no-data"> 沒有找到匹配的數據 </div> </div> <!-- 相关病态区域 --> <div class="relative-area"> <mrrelate v-if="showRelative" :currentCase="currentCase" :allTags="api2Data" @data-updated="handleDataUpdated"></mrrelate> <!-- 添加事件监听 --> <span v-else>顯示醫案相關專有名詞</span> </div> </div> </template> <script> import mrrelate from './mrrelate.vue'; export default { name: 'mrviewer', components: { mrrelate }, data() { return { api1Data: [], api2Data: [], mergedData: [], currentPage: 1, pageSize: 1, searchQuery: '', sortKey: '', sortOrders: {}, inputPage: 1, fieldNames: { 'mrcase': '醫案全文', 'mrname': '醫案命名', 'mrposter': '醫案提交者', 'mrlasttime': '最後編輯時間', 'mreditnumber': '編輯次數', 'mrreadnumber': '閱讀次數', 'mrpriority': '重要性', 'dntag': '病態名稱' }, inputTimeout: null, dnNames: [], stateVersion: '1.0', showRelative: false, currentCase: null // 存储当前医案完整数据 }; }, computed: { filteredData() { const query = this.searchQuery.trim(); if (query && /^\d+$/.test(query)) { const idToSearch = parseInt(query, 10); return this.mergedData.filter(item => item.id === idToSearch); } if (!query) return this.mergedData; const lowerQuery = query.toLowerCase(); return this.mergedData.filter(item => { return Object.values(item).some(value => { if (value === null || value === undefined) return false; if (Array.isArray(value)) { return value.some(subValue => { if (typeof subValue === 'object' && subValue !== null) { return JSON.stringify(subValue).toLowerCase().includes(lowerQuery); } return String(subValue).toLowerCase().includes(lowerQuery); }); } if (typeof value === 'object' && value !== null) { return JSON.stringify(value).toLowerCase().includes(lowerQuery); } return String(value).toLowerCase().includes(lowerQuery); }); }); }, sortedData() { if (!this.sortKey) return this.filteredData; const order = this.sortOrders[this.sortKey] || 1; return [...this.filteredData].sort((a, b) => { const getValue = (obj) => { const val = obj[this.sortKey]; if (Array.isArray(val)) return JSON.stringify(val); return val; }; const aValue = getValue(a); const bValue = getValue(b); if (aValue === bValue) return 0; return aValue > bValue ? order : -order; }); }, paginatedData() { const start = (this.currentPage - 1) * Number(this.pageSize); const end = start + Number(this.pageSize); const data = this.sortedData.slice(start, end); // 更新当前医案完整数据 if (data.length > 0) { this.currentCase = data[0]; } else { this.currentCase = null; } return data; }, totalPages() { return Math.ceil(this.filteredData.length / this.pageSize) || 1; } }, watch: { pageSize() { this.currentPage = 1; this.inputPage = 1; this.saveState(); }, currentPage(newVal) { this.inputPage = newVal; this.saveState(); }, filteredData() { if (this.currentPage > this.totalPages) { this.currentPage = Math.max(1, this.totalPages); } this.inputPage = this.currentPage; }, searchQuery() { this.saveState(); } }, methods: { // 新增方法:处理数据更新事件 handleDataUpdated() { // 显示操作成功的提示 alert('MRDN數據已更新,正在刷新醫案數據...'); // 刷新数据 this.fetchData(); }, saveState() { const state = { version: this.stateVersion, currentPage: this.currentPage, pageSize: this.pageSize, searchQuery: this.searchQuery, timestamp: new Date().getTime() }; sessionStorage.setItem('mrviewerState', JSON.stringify(state)); }, restoreState() { const savedState = sessionStorage.getItem('mrviewerState'); if (!savedState) return; try { const state = JSON.parse(savedState); if (state.version !== this.stateVersion) return; this.currentPage = state.currentPage || 1; this.pageSize = state.pageSize || 1; this.searchQuery = state.searchQuery || ''; this.inputPage = this.currentPage; } catch (e) { sessionStorage.removeItem('mrviewerState'); } }, clearState() { sessionStorage.removeItem('mrviewerState'); }, async fetchData() { try { const api1Response = await fetch("MRInfo/?format=json"); this.api1Data = await api1Response.json(); const api2Response = await fetch("DNTag/?format=json"); this.api2Data = await api2Response.json(); this.dnNames = this.api2Data.map(item => item.dnname).filter(name => name && name.trim()); this.dnNames.sort((a, b) => b.length - a.length); this.mergeData(); this.currentPage = 1; this.inputPage = 1; this.saveState(); } catch (error) { console.error("獲取數據失敗:", error); alert("數據加載失敗,請稍後重試"); } }, mergeData() { this.mergedData = this.api1Data.map((item) => { const newItem = { ...item }; if (newItem.dntag && Array.isArray(newItem.dntag)) { newItem.dntag = newItem.dntag.map((tagId) => { const matchedItem = this.api2Data.find(api2Item => api2Item.id === tagId); return matchedItem || { id: tagId, dnname: "未找到匹配的數據" }; }); } return newItem; }); this.sortOrders = {}; if (this.mergedData.length > 0) { Object.keys(this.mergedData[0]).forEach(key => { this.sortOrders[key] = 1; }); } }, processFieldNames(item) { const result = {}; for (const key in item) { const newKey = this.fieldNames[key] || key; result[newKey] = item[key]; } return result; }, highlightMatches(text) { if (!text || typeof text !== 'string' || this.dnNames.length === 0) { return text; } const pattern = new RegExp( this.dnNames .map(name => name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')) .join('|'), 'gi' ); return text.replace(pattern, match => `<span style="color: rgb(212, 107, 8); font-weight: bold;">${match}</span>` ); }, formatValue(value, fieldName) { if (value === null || value === undefined) return ''; if (fieldName === '醫案全文' && typeof value === 'string') { return this.highlightMatches(value); } if (typeof value === 'string' && value.startsWith('http')) { return `<a href="${value}" target="_blank">${value}</a>`; } return value; }, formatDntagValue(dntagArray) { return dntagArray.map(tagObj => { return tagObj.dnname || tagObj.name || '未命名標籤'; }).join(';'); }, sortBy(key) { const originalKey = Object.keys(this.fieldNames).find( origKey => this.fieldNames[origKey] === key ) || key; this.sortKey = originalKey; this.sortOrders[originalKey] = this.sortOrders[originalKey] * -1; this.saveState(); }, prevPage() { if (this.currentPage > 1) { this.currentPage--; this.saveState(); } }, nextPage() { if (this.currentPage < this.totalPages) { this.currentPage++; this.saveState(); } }, handlePageInput() { clearTimeout(this.inputTimeout); this.inputTimeout = setTimeout(() => { this.goToPage(); this.saveState(); }, 300); }, goToPage() { if (this.inputPage === null || this.inputPage === undefined || this.inputPage === '') { this.inputPage = this.currentPage; return; } const page = parseInt(this.inputPage); if (isNaN(page)) { this.inputPage = this.currentPage; return; } if (page < 1) { this.currentPage = 1; } else if (page > this.totalPages) { this.currentPage = this.totalPages; } else { this.currentPage = page; } this.inputPage = this.currentPage; }, toggleRelative() { this.showRelative = !this.showRelative; } }, mounted() { this.restoreState(); this.fetchData(); }, activated() { this.restoreState(); }, deactivated() { this.saveState(); } }; </script> <style scoped> .container { max-width: 1200px; margin: 0px; padding: 0px; } .control-panel { margin-bottom: 0px; display: flex; flex-wrap: wrap; gap: 10px; justify-content: flex-end; align-items: center; position: fixed; bottom: 0; left: 0; width: 100%; background-color: #ffd800ff; z-index: 999; padding: 10px 20px; box-sizing: border-box; } .content-area { position: fixed; top: 56px; bottom: 100px; left: 0; width: 70%; background: white; padding: 1px; z-index: 100; overflow-y: auto; } .relative-area { position: fixed; top: 56px; bottom: 100px; right: 0; width: 30%; background: lightblue; padding: 1px; z-index: 100; overflow-y: auto; } .refresh-btn, .relative-btn { padding: 4px; background-color: #4CAF50; color: white; border: none; border-radius: 4px; cursor: pointer; } .refresh-btn:hover, .relative-btn:hover { background-color: #45a049; } .search-input { padding: 8px; border: 1px solid #ddd; border-radius: 4px; flex-grow: 1; max-width: 300px; } .pagination-controls { display: flex; align-items: center; gap: 5px; } .page-size-select { padding: 4px; border-radius: 4px; width: 70px; } .page-input { width: 50px; padding: 4px; border: 1px solid #ddd; border-radius: 4px; text-align: center; } .horizontal-records { display: flex; flex-direction: column; gap: 20px; } .record-card { border: 1px solid #ddd; border-radius: 4px; overflow: hidden; box-shadow: 0 2px 4px rgba(0,0,0,0.1); } .record-header { padding: 12px 16px; background-color: #f5f5f5; border-bottom: 1px solid #ddd; } .record-header h3 { margin: 0; font-size: 1.1em; } .record-body { padding: 16px; } .record-field { display: flex; margin-bottom: 12px; line-height: 1.5; } .record-field:last-child { margin-bottom: 0; } .field-name { font-weight: bold; min-width: 120px; color: #555; } .field-value { flex-grow: 1; display: flex; flex-wrap: wrap; gap: 8px; } .dntag-value { display: flex; flex-wrap: wrap; gap: 8px; } .array-value { display: flex; flex-wrap: wrap; gap: 8px; } .no-data { padding: 20px; text-align: center; color: #666; font-style: italic; } button:disabled { opacity: 0.5; cursor: not-allowed; } </style> mrrelate.vue: <template> <div class="mrrelate-container"> <!-- 相关病态区域(上方) --> <div class="tags-section"> <h3>尚未與此醫案關聯的病態列表</h3> <div class="filter-info" v-if="filteredTags.length > 0"> 顯示與當前醫案不同但相關的病態標籤({{ filteredTags.length }}個) </div> <div v-if="filteredTags.length > 0" class="dntag-list"> <div v-for="(tag, index) in filteredTags" :key="tag.id" class="dntag-item"> <div class="tag-content"> <span class="tag-index">{{ index + 1 }}.</span> <span class="tag-name">{{ tag.id }}: {{ tag.dnname || '未命名標籤' }}</span> </div> </div> </div> <div v-else class="no-tags"> 沒有符合條件的相關病態標籤 </div> </div> <!-- 分隔线 --> <div class="divider"></div> <!-- MRDN数据区域(下方) --> <div class="mrdn-section"> <h3>醫案病態關聯管理</h3> <!-- 操作按钮 --> <div class="mrdn-controls"> <button @click="fetchMRDNData" class="refresh-btn">刷新數據</button> <button @click="manualCreateMRDN" class="create-btn">手動新增醫案病態關聯</button> </div> <!-- 数据列表 --> <div v-if="mrdnData.length > 0" class="mrdn-list"> <table class="mrdn-table"> <thead> <tr> <th>ID</th> <th>醫案ID</th> <th>病態ID</th> <th>操作</th> </tr> </thead> <tbody> <tr v-for="item in mrdnData" :key="item.id"> <td>{{ item.id }}</td> <td> <span v-if="!item.editing">{{ item.mrinfo }}</span> <textarea v-else v-model="item.editData.mrinfo" class="edit-textarea"></textarea> </td> <td> <span v-if="!item.editing">{{ item.dntag }}</span> <input v-else v-model="item.editData.dntag" type="text" class="edit-input"> </td> <td class="actions"> <template v-if="!item.editing"> <button @click="startEdit(item)" class="edit-btn">編輯</button> <button @click="confirmDelete(item.id)" class="delete-btn">刪除</button> </template> <template v-else> <button @click="saveEdit(item)" class="save-btn">保存</button> <button @click="cancelEdit(item)" class="cancel-btn">取消</button> </template> </td> </tr> </tbody> </table> </div> <div v-else class="no-data"> 沒有醫案病態關聯數據 </div> </div> </div> </template> <script> export default { name: 'mrrelate', props: { currentCase: { type: Object, default: null }, allTags: { type: Array, required: true } }, data() { return { mrdnData: [], // 存储MRDN数据 isCreating: false, // 自动创建状态 hasAutoCreated: false // 新增:标记是否已自动执行 }; }, computed: { filteredTags() { if (!this.currentCase) return []; const currentTagIds = this.currentCase.dntag ? this.currentCase.dntag.map(tag => tag.id) : []; const caseContent = this.currentCase.mrcase || ''; const contentLower = caseContent.toLowerCase(); return this.allTags.filter(tag => { if (currentTagIds.includes(tag.id)) return false; if (!tag.dnname) return false; return contentLower.includes(tag.dnname.toLowerCase()); }); } }, watch: { // 监听currentCase变化(包含立即执行选项) currentCase: { immediate: true, handler(newVal) { if (newVal && newVal.id) { // 确保只执行一次 if (!this.hasAutoCreated) { this.autoCreateMRDN(); this.hasAutoCreated = true; } } } } }, methods: { // 获取MRDN数据 async fetchMRDNData() { try { const response = await fetch("MRDN/?format=json"); const data = await response.json(); // 确保字段名称正确映射 this.mrdnData = data.map(item => ({ id: item.id, mrinfo: item.mrinfo || '', // 医案全文 dntag: item.dntag || '', // 病态名称 editing: false, editData: { mrinfo: item.mrinfo || '', dntag: item.dntag || '' } })); } catch (error) { console.error("獲取MRDN數據失敗:", error); alert("MRDN數據加載失敗"); } }, // 自动创建新MRDN async autoCreateMRDN() { if (this.isCreating) return; // 检查当前医案和病态标签 if (!this.currentCase || !this.currentCase.id) { console.log('沒有當前的醫案數據,自動創建跳過'); return; } if (this.filteredTags.length === 0) { console.log('沒有相關的病態標籤,自動創建跳過'); return; } try { this.isCreating = true; // 构建批量创建数据 const createRequests = this.filteredTags.map(tag => { return fetch("MRDN/", { method: "POST", headers: { "Content-Type": "application/json", "X-CSRFToken": this.getCSRFToken() }, body: JSON.stringify({ mrinfo: `${this.currentCase.id}`, // 使用当前医案ID dntag: `${tag.id}` // 使用病态标签ID }) }); }); // 执行所有创建请求 const responses = await Promise.all(createRequests); const allSuccess = responses.every(res => res.ok); if (allSuccess) { console.log(`成功新增 ${this.filteredTags.length} 筆MRDN數據!`); this.fetchMRDNData(); // 刷新数据 this.triggerDataUpdate(); // 通知父组件 } else { throw new Error("部分新增失敗"); } } catch (error) { console.error("批量新增MRDN失敗:", error); } finally { this.isCreating = false; } }, // 手动创建MRDN(按钮功能保留) async manualCreateMRDN() { try { await this.autoCreateMRDN(); if (this.filteredTags.length > 0) { alert(`成功新增 ${this.filteredTags.length} 筆MRDN數據!`); } } catch (error) { alert("新增過程中發生錯誤"); } }, // 开始编辑 startEdit(item) { item.editing = true; item.editData = { mrinfo: item.mrinfo, dntag: item.dntag }; }, // 取消编辑 cancelEdit(item) { item.editing = false; }, // 保存编辑 async saveEdit(item) { try { const response = await fetch(`MRDN/${item.id}/`, { method: "PUT", headers: { "Content-Type": "application/json", "X-CSRFToken": this.getCSRFToken() }, body: JSON.stringify({ mrinfo: item.editData.mrinfo, dntag: item.editData.dntag }) }); if (response.ok) { item.mrinfo = item.editData.mrinfo; item.dntag = item.editData.dntag; item.editing = false; alert("更新成功!"); // 触发数据更新事件 this.triggerDataUpdate(); } else { throw new Error("更新失敗"); } } catch (error) { console.error("更新MRDN失敗:", error); alert("更新失敗"); } }, // 删除确认 confirmDelete(id) { if (confirm("確定要刪除此數據嗎?")) { this.deleteMRDN(id); } }, // 删除MRDN async deleteMRDN(id) { try { const response = await fetch(`MRDN/${id}/`, { method: "DELETE", headers: { "X-CSRFToken": this.getCSRFToken() } }); if (response.ok) { this.mrdnData = this.mrdnData.filter(item => item.id !== id); alert("刪除成功!"); // 触发数据更新事件 this.triggerDataUpdate(); } else { throw new Error("刪除失敗"); } } catch (error) { console.error("刪除MRDN失敗:", error); alert("刪除失敗"); } }, // 获取CSRF Token getCSRFToken() { return document.querySelector('[name=csrfmiddlewaretoken]')?.value || ''; }, // 触发数据更新事件 triggerDataUpdate() { this.$emit('data-updated'); } }, mounted() { this.fetchMRDNData(); // 确保在组件挂载时检查一次 if (this.currentCase && this.currentCase.id && !this.hasAutoCreated) { this.autoCreateMRDN(); this.hasAutoCreated = true; } } }; </script> <style scoped> .mrrelate-container { padding: 15px; background: lightblue; height: 100%; overflow-y: auto; display: flex; flex-direction: column; gap: 15px; } /* 相关病态区域样式 */ .tags-section { flex: 0 0 40%; /* 固定高度占比 */ overflow-y: auto; background: rgba(255, 255, 255, 0.3); border-radius: 8px; padding: 15px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); } /* 分隔线样式 */ .divider { height: 2px; background: #3498db; margin: 10px 0; } /* MRDN数据区域样式 */ .mrdn-section { flex: 1; /* 占据剩余空间 */ overflow-y: auto; background: rgba(255, 255, 255, 0.3); border-radius: 8px; padding: 15px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); } h3 { margin-top: 0; padding-bottom: 8px; color: #2c3e50; text-align: center; border-bottom: 2px solid #3498db; } .filter-info { text-align: center; margin: 10px 0; font-size: 0.9em; color: #555; background: rgba(255, 255, 255, 0.3); padding: 5px; border-radius: 4px; } .dntag-list { display: grid; grid-template-columns: 1fr; gap: 12px; margin-top: 15px; } .dntag-item { background: #fff; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); overflow: hidden; transition: all 0.3s ease; border-left: 4px solid #3498db; } .tag-content { padding: 12px 15px; display: flex; align-items: center; } .tag-index { font-weight: bold; margin-right: 10px; min-width: 25px; height: 25px; display: flex; align-items: center; justify-content: center; background: #3498db; color: white; border-radius: 50%; } .tag-name { flex-grow: 1; font-weight: 500; color: #2c3e50; } .no-tags, .no-data { padding: 25px; text-align: center; color: #666; font-style: italic; margin-top: 20px; border: 1px dashed #3498db; border-radius: 8px; background: rgba(255, 255, 255, 0.5); } /* MRDN数据管理样式 */ .mrdn-controls { display: flex; justify-content: space-between; margin-bottom: 15px; } .mrdn-controls button { padding: 6px 12px; border-radius: 4px; border: none; cursor: pointer; font-weight: bold; } .refresh-btn { background-color: #4CAF50; color: white; } .create-btn { background-color: #2196F3; color: white; } .mrdn-table { width: 100%; border-collapse: collapse; background: white; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1); } .mrdn-table th, .mrdn-table td { padding: 12px 15px; text-align: left; border-bottom: 1px solid #eee; } .mrdn-table th { background-color: #3498db; color: white; font-weight: bold; } .mrdn-table tr:hover { background-color: #f5f5f5; } .actions { display: flex; gap: 5px; } .actions button { padding: 5px 10px; border: none; border-radius: 3px; cursor: pointer; font-size: 0.85em; } .edit-btn { background-color: #FFC107; color: #333; } .delete-btn { background-color: #F44336; color: white; } .save-btn { background-color: #4CAF50; color: white; } .cancel-btn { background-color: #9E9E9E; color: white; } .edit-input, .edit-textarea { width: 100%; padding: 5px; border: 1px solid #ddd; border-radius: 3px; } .edit-textarea { min-height: 60px; resize: vertical; } </style>
最新发布
07-21
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值