嵌套页面传参parent.$("body").data();

本文介绍了一种利用jQuery在父页面与子页面之间传递数据的方法。通过将数据存储在父页面的body元素中,子页面可以通过jQuery获取这些数据并进行展示。此方法适用于有嵌套关系的页面。

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

一.分析

父页面: parent.$("body").data("aintt_val", str);  // 存储参数

子页面:var str = parent.$("body").data("aintt_val");//取参数

$("#bdiv").html(str); //显示内容

二注意

1.此方法俩个页面必须是嵌套关系(也可以用layer 中iframe层的显示)

2. parent.$("body").data("aintt_val", str);  中的 aintt_val 是可以随意设置 (是数据str 的名称) str是数据

3.子页面是获取数据str的名称,从而得到数据

4.jQuery.data() 参考

三.列子

1.jsonForm.txt

{
	"brxm00": "陈步卜",
	"brxb00": "男",
	"age": "25岁",
	"sqysxm":"吴聊聊",
	"sqrqsj": "2018-01-17 10:36:17",
	"txm000": "2018011711",
	"zyhghh": "0987654321",
	"cjrxm0":"莫年华",
	"pyrq00": "2018-01-18",
	"pysj00": "15:36:18",
	"ch0000": "34556",
	"sqksmc": "急诊科",
	"shrq00": "2018-01-16",
	"shsj00": "15:36:00",
	"bblxmc":"血清",
	"dyrq00":"2018-01-18",
	"dysj00":"13:54:10",
	"pyr000":"吴晓峰",
	"shr000":"沈天明"
}


2.index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
	<title>test</title>
	<script src="jQuery-2.1.4.min.js"></script>
</head>
<body>
<div>
	<div>
		<input id="aintt" type="text" />
		<input id="abtn" type="button" value="测试"/>
	</div>
	<div>
		<iframe id="iframe" style="width:400px;height:300px;"></iframe>
	</div>
</div>
</body>
<script>
$(function(){
	$("#abtn").on("click",function(){
		var str = $("#aintt").val();//1.直接输入值传过去
		if(!str){
			str="未输入,默认为空。";
		}
		parent.$("body").data("aintt_val", str);//1.1存储直接输入的值
		$.getJSON('jsonForm.txt',function(data){  //2.获取json数据 
	             var obj=data;
	             parent.$("body").data("jsonForm_val", obj);//2.2  存储json数据
	        }); 
		
		$("#iframe").attr("src","./child1.html?22");//嵌套页面
		
	});

});
</script>
</html>
2.child1.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
	<title>test</title>
	<script src="jQuery-2.1.4.min.js"></script>
</head>
<body>
<div>
	<div>从index.html传过来的值为:<lable id="bdiv"></label></div>
	<h1>json传值过来:</h1>
	<form class="print-info clearfix" id="print-info">  
        <div class="print-info-row">  
            <label>姓名:</label>  
            <input type="text" name="brxm00" value="小小高">  
        </div>  
        <div class="print-info-row" style="width: 190px;">  
            <label>门  诊  号:</label>  
            <input type="text" name="zyhghh" value="12345678" >  
        </div>  
        <div class="print-info-row"  style="width: 214px;">  
            <label>申请医生:</label>  
            <input type="text" name="sqysxm" value="小高高" >  
        </div>  
         <div class="print-info-row"  style="width: 220px;margin: 0px 0 0px;">  
            <label>申请时间:</label>  
            <input type="text" name="sqrqsj" value="2018-01-16 10:36" >  
        </div>  
        <div class="print-info-row">  
            <label>性别:</label>  
            <input type="text" name="brxb00" value="女">  
        </div>  
    </form>  
</div>
</body>
<script>
$(function(){
	var str = parent.$("body").data("aintt_val");//1.取出父页面直接输入的值
	$("#bdiv").html(str);//1.1直接显示 父页面输入的值
	var obj= parent.$("body").data("jsonForm_val");//2.取出父页面穿过来的json数据
	$("#print-info").setForm(obj);  //2.2把json数据现在form中
});
$.fn.setForm = function(jsonValue){    
    var obj=this;    
    $.each(jsonValue, function (name, ival) {    
        var $oinput = obj.find("input[name=" + name + "]");     
        if ($oinput.attr("type")== "radio" || $oinput.attr("type")== "checkbox"){    
             $oinput.each(function(){    
                 if(Object.prototype.toString.apply(ival) == '[object Array]'){//是复选框,并且是数组    
                      for(var i=0;i<ival.length;i++){    
                          if($(this).val()==ival[i])    
                             $(this).attr("checked", "checked");    
                      }    
                 }else{    
                     if($(this).val()==ival)    
                        $(this).attr("checked", "checked");    
                 }    
             });    
        }else if($oinput.attr("type")== "textarea"){//多行文本框    
            obj.find("[name="+name+"]").html(ival);    
        }else{    
             obj.find("[name="+name+"]").val(ival);     
        }    
   });    
}  
</script>
</html>

<template> <div class="addTaskModal" v-if="visible"> <editAndAddPage :router="'/basicConfiguration'" :title="titles" @cancel="cancel" @submit="submit"> <template v-slot:pageBody> <div class="main-body-box"> <a-form-model :label-col="{ span: 2 }" :wrapper-col="{ span: 22 }" ref="ruleForm" :rules="rules" :model="modalData" > <a-form-model-item label=""></a-form-model-item> <a-form-model-item :label="$t('任务名称:')" prop="taskName"> <a-input :placeholder="$t('请输入任务名称')" v-model="modalData.taskName" maxLength="25"> </a-input> </a-form-model-item> <a-form-model-item :label="$t('包含设备:')"> <Transfer ref="transferRef" :hostModel="modalData.hostModel"></Transfer> </a-form-model-item> <a-form-model-item :label="$t('空开配置:')"> <div class="config_content"> <div class="config_item" v-for="(item, index) in configArr" :key="index"> <div class="config_title"> <a-select v-model="item.configTypeCode" @change="value => handleConfigTypeChange(index, value)" :placeholder="$t('请选择')" > <a-select-option :value="el.configTypeCode" v-for="el in getAvailableOptions(index)" :key="el.configTypeCode" :title="$t(el.configTypeName)" > {{ $t(el.configTypeName) }} </a-select-option> </a-select> <hd-icon type="delete" @click="delConfig(index)" /> </div> <div class="config_main"> <div class="type_info"> <span>{{ $t('操作类型:') }}</span> <a-radio-group v-model="item.cmd" @change="onChange"> <a-radio-button value="0"> {{ $t('分闸') }}</a-radio-button> <a-radio-button value="1"> {{ $t('合闸') }} </a-radio-button> </a-radio-group> </div> <div class="time_info"> <span>{{ $t('时间范围:') }}</span> <a-time-picker class="mgb_12" format="HH:mm" valueFormat="HH:mm" v-model="item.excTime" :placeholder="$t('选择时间')" /> </div> <div class="week_info"> <span>{{ $t('运行周期:') }}</span> <div class="week_list"> <div class="week_item" v-for="(day, indx) in item.weekList" :key="indx" @click="toggleDay(day, item)" :class="{ selected: day.value == 1 }" > <div>{{ day.name }}</div> <div v-show="day.value == 1" class="triangle"></div> <div v-show="day.value == 1" class="checkmark"></div> </div> </div> </div> </div> </div> </div> <div class="addBtn" @click="addConfig"> <hd-icon type="add" /> {{ $t('新增空开配置') }} </div> </a-form-model-item> </a-form-model> </div> </template> </editAndAddPage> </div> </template> <script> import reg from '@/common/js/reg' import factory from '../factory' import Transfer from './Transfer.vue' import editAndAddPage from '@/components/scfComponents/editAndAddPage/editAndAddPage.vue' export default { components: { Transfer, editAndAddPage }, data() { return { titles: '新增空开定时任务', visible: false, modalData: { taskName: '', hostModel: undefined, }, rules: { taskName: [ { required: true, message: '请输入任务名称', trigger: 'blur' }, { pattern: reg.name, message: this.$t('仅允许输入汉字、字母、数字与_-.@字符') }, ], }, selectedConfigTypes: new Set(), // 存储已选的配置类型编码 configArr: [ { cmd: '', excTime: '', weekList: [ { name: '周日', value: 0 }, { name: '周一', value: 0 }, { name: '周二', value: 0 }, { name: '周三', value: 0 }, { name: '周四', value: 0 }, { name: '周五', value: 0 }, { name: '周六', value: 0 }, ], }, ], } }, computed: { allConfigOptions() { const arr = [] for (let i = 0; i < 31; i++) { const configTypeCode = (1026 + i).toString() arr.push({ configTypeCode, configTypeName: this.$t('空开配置') + i, }) } return arr }, }, mounted() {}, methods: { // 打开弹窗 showModal() { this.visible = true // 获取主机型号 this.modalData = { taskName: '', hostModel: undefined, } }, // 获取指定配置项可用的选项 getAvailableOptions(index) { const currentSelected = this.configArr[index].configTypeCode return this.allConfigOptions.filter(option => { // 当前项已选中的配置始终可用 if (option.configTypeCode === currentSelected) return true // 其他配置未被选中时可用 return !this.selectedConfigTypes.has(option.configTypeCode) }) }, // 处理配置类型变更 handleConfigTypeChange(index, value) { const prevValue = this.configArr[index].configTypeCode // 移除旧值 if (prevValue) { this.selectedConfigTypes.delete(prevValue) } // 添加新值 if (value) { this.selectedConfigTypes.add(value) } // 更新配置项的值 this.$set(this.configArr, index, { ...this.configArr[index], configTypeCode: value, }) }, toggleDay(day, item) { day.value = day.value == 0 ? 1 : 0 const values = item.weekList.map(day => day.value) item.configValue.rept = values.join('') + '00' }, // 添加配置项 addConfig() { this.configArr.push({ cmd: '', excTime: '', weekList: [ { name: '周日', value: 0 }, { name: '周一', value: 0 }, { name: '周二', value: 0 }, { name: '周三', value: 0 }, { name: '周四', value: 0 }, { name: '周五', value: 0 }, { name: '周六', value: 0 }, ], }) }, // 删除配置项 delConfig(index) { if (this.configArr.length == 1) { this.$message.destroy() this.$message.warning(this.$t('至少保留一个配置项')) } else { // 移除该配置项占用的类型 const removedConfig = this.configArr[index] if (removedConfig.configTypeCode) { this.selectedConfigTypes.delete(removedConfig.configTypeCode) } this.configArr.splice(index, 1) } }, // 取消 cancel() { this.visible = false }, // 确定 submit() { this.$refs.ruleForm.validate(valid => { if (!valid) return const detectorList = this.$refs.transferRef.getSelectedData() || [] if (detectorList.length === 0) { this.$message.destroy() this.$message.warning(this.$t('请选择设备列表')) return } let errMsg = '' let configs = this.configArr.filter(item => item.isCheck) if (configs.length === 0) { errMsg = this.$t('请选择配置定时开合闸') } else { for (let i = 0; i < configs.length; i++) { const { configValue, configTypeName, cmd, excTime } = configs[i] if (cmd == null || cmd === '' || (typeof cmd === 'string' && cmd.trim() === '')) { errMsg = `${this.$t('请选择')}${configTypeName}${this.$t('分合闸')}` break } else if (!excTime) { errMsg = `${this.$t('请选择')}${configTypeName}${this.$t('时间')}` break } else if (!configValue.rept || configValue.rept == '000000000') { errMsg = `${this.$t('请选择')}${configTypeName}${this.$t('周期')}` break } configValue.cmd = cmd configValue.excTime = moment(excTime, 'HH:mm').valueOf() configValue.time = moment().valueOf() } } if (errMsg) { this.$message.destroy() this.$message.warning(errMsg) return } let params = { commandMode: '0', // 配置模式 主机0 探测器1 issueType: '1', // 1为首次下发 2为重新下发 jobName: this.modalData.taskName, userCode: localStorage.getItem('userId'), detectorList: detectorList.map(item => ({ ...item, channelNo: `${item.systemAddress}@${item.partUnitLoopCode}@${item.channelNo}`, })), configs, } console.log(params) factory.batchConfig(params).then(res => { if (res.success) { this.$message.destroy() this.$message.success('操作成功') this.handleCancel() this.$parent.getTableList() } }) }) }, }, } </script> <style lang="less" scoped> .addTaskModal { width: 100%; height: 100%; text-align: left; box-sizing: border-box; } .main-body-box { .config_content { border-radius: 4px; border: 1px solid #ebedef; .config_title { height: 48px; display: flex; align-items: center; padding: 0 16px; border-bottom: 1px solid rgb(229, 231, 234); background: rgb(242, 243, 244); justify-content: space-between; } .config_main { height: 176px; padding: 16px; display: flex; flex-direction: column; justify-content: space-around; align-items: flex-start; color: rgb(105, 118, 136); font-family: '阿里巴巴普惠体'; font-size: 14px; font-weight: 400; background: rgb(255, 255, 255); .type_info { display: flex; align-items: center; } .week_info { display: flex; align-items: center; .week_list { display: flex; .week_item { height: 40px; width: 82px; display: flex; cursor: default; align-items: center; justify-content: center; position: relative; border: 1px solid rgb(217, 220, 224); border-radius: 4px; margin-right: 12px; color: rgb(105, 118, 136); font-family: '阿里巴巴普惠体'; font-size: 14px; font-weight: 400; &.selected { color: #006fff; border: 1px solid rgb(0, 111, 255); } .triangle { position: absolute; bottom: 0; right: 0; width: 0; height: 0; border-style: solid; border-width: 0 0 24px 24px; border-color: transparent transparent #006fff transparent; } /* 对勾实现 */ .checkmark { position: absolute; bottom: 5px; /* 调整位置使其在三角形内居中 */ right: 4px; /* 调整位置使其在三角形内居中 */ width: 8px; height: 5px; transform: rotate(-45deg); &::before { content: ''; position: absolute; width: 2px; height: 5px; background-color: white; left: 0; top: 0; } &::after { content: ''; position: absolute; width: 6px; height: 2px; background-color: white; right: 0; bottom: 0; } } } } } span { margin-right: 8px; } } } .addBtn { width: 100%; height: 32px; cursor: default; display: flex; align-items: center; justify-content: center; border-radius: 4px; margin-top: 12px; color: rgb(41, 141, 255); border: 1px dashed rgb(41, 141, 255); background: rgba(41, 141, 255, 0.1); } } </style> 代码评审
最新发布
08-02
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值